user2536680
user2536680

Reputation: 79

Extract subarray of each chunk and convert to string

My code is as the following:

$text = "john1,steven2,lex66,e1esa2,444e3, and so forth[...]"; // up to about 180 entries
$arrayChunk = array_chunk(explode(',', $text), 39); // which leaves me with 5 chunks

foreach ($arrayChunk as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $subkey => $subvalue) {
            $string = $subvalue;
        }
        echo $string; // echo all the subvalues (but only echos the first)
    }
}

So, I end up with 5 chunks, and I need foreach to echo all the subvalues of the array like this:

john1,steven2,[...]
doe4,joe7,[...]
svend2,ole5[...]
olga7,jan3[...]
leila9,aija9[...]

instead of just

john1
doe4
svend2
olga7
leila9

Upvotes: 0

Views: 155

Answers (3)

mickmackusa
mickmackusa

Reputation: 47992

Rather than explode(), array_chunk(), foreach(), is_array(), implode(), I recommend a more direct regex approach.

My method splits your string on the 39th comma -- no extra handling, simple.

Code: (Demo)

$text="a,b,c,d,e,f,g,h,i,10,a,b,c,d,e,f,g,h,i,20,a,b,c,d,e,f,g,h,i,30,a,b,c,d,e,f,g,h,i,40,a,b,c,d,e,f,g,h,i,50";
$groups=preg_split('/(?:[^,]+\K,){39}/',$text);
foreach($groups as $group){
    echo "$group\n";
}

Output:

a,b,c,d,e,f,g,h,i,10,a,b,c,d,e,f,g,h,i,20,a,b,c,d,e,f,g,h,i,30,a,b,c,d,e,f,g,h,i
40,a,b,c,d,e,f,g,h,i,50

The pattern will match the values followed by a comma 39-times and restart the fullstring match (using \K) on the trailing comma -- this restart means that there will be no trailing comma on any of the strings in $groups.

Here is a Pattern Demo.

Upvotes: 0

user2687506
user2687506

Reputation: 800

You are using:

 $string = $subvalue;

And then only outputting one. If you want to echo all, use implode:

 foreach ($arrayChunk as $key => $value)
    {
            if (is_array($value))
            {
                 echo implode(', ', $value) . "<br>";
            }
    }

Upvotes: 1

Kumar Saurabh Sinha
Kumar Saurabh Sinha

Reputation: 870

  1. Addecho implode(', ', $value);
  2. Add echo "<br>"; for line break

    foreach ($arrayChunk as $key => $value)
            {
                    if (is_array($value))
                    {
    
                         echo implode(', ', $value);
                         echo "<br>";
                    }
            }
    

Upvotes: 0

Related Questions