0

Lets say I have the following array:

$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);

What I'm now trying to do is to convert this array into a multidimensional array every time the number changes in the key.

I know we have to use explode("__", $key), but I can't work out how to convert it to a multidimensional array so it would appear something like the following:

Array
(
 Array
 ( 
  [exercise__2] => Then a set
  [sets__2] => 3
 )
 Array
 (
  [exercise__4] => And finally a set
  [sets__4] => 3
 )
)

I suspect it's not too difficult but I'm frying my brain trying to work it out.

dWinder
  • 11,597
  • 3
  • 24
  • 39
jimbeeer
  • 1,604
  • 2
  • 12
  • 25
  • 2
    Hi, show us what you have done so far – RiggsFolly May 07 '19 at 15:40
  • Possible duplicate of [How to convert a simple array to an associative array?](https://stackoverflow.com/questions/6153360/how-to-convert-a-simple-array-to-an-associative-array) – Script47 May 07 '19 at 15:43

2 Answers2

1

Simple for loop should do it:

$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
foreach($arr as $k =>$v) {
    $res[explode("__", $k)[1]][$k] = $v;
}

You can use array_values if you don't want the extra key in the upper array.

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
0

Array_chunk seems to be enough.
Array_chunk splits an array with n number of items.
The third argument is to preserve keys.

$arr = array("exercise__2" => "Then a set", "sets__2" => 3, "exercise__4" => "And finally a set", "sets__4" => 3);
$result = array_chunk($arr, 2, true);
print_r($result);

Output:

Array
(
    [0] => Array
        (
            [exercise__2] => Then a set
            [sets__2] => 3
        )

    [1] => Array
        (
            [exercise__4] => And finally a set
            [sets__4] => 3
        )

)

https://3v4l.org/s57ua

Andreas
  • 23,610
  • 6
  • 30
  • 62