How to divide the php array in to multidimensional array? please see below-ThrowExceptions

Exception or error:

I have the array which looks like below, this data coming from the form which has dynamic fields.

Array
(
    [package-name-1] => package1
    [package-serve-1] => sdasd
    [package-price-date-1] => 31-03-2020   
    [foodType-1-1] => Rice
    [foodTags-1-1] => rice
    [foodNotes-1-1] => notes
    [foodchoose-1-1] => 0
    [package-name-2] => package2
    [package-serve-2] => Leaf
    [package-price-date-2] => 12-08-2020
    [foodType-2-2] => rice1
    [foodTags-2-2] => rice1
    [foodNotes-2-2] => dasd
    [foodchoose-2-2] => 3
    [foodType-2-3] => rice2
    [foodTags-2-3] => rice2
    [foodNotes-2-3] => qwewe
    [foodchoose-2-3] => 0
)

I want the array output like below, like in two array, array should break from [package-name] key and move into separate array. Output should be like:

array(
  [0]=>array(
          [package-name-1] => package1
          [package-serve-1] => sdasd
          [package-price-date-1] => 31-03-2020   
          [foodType-1-1] => Rice
          [foodTags-1-1] => rice
          [foodNotes-1-1] => notes
          [foodchoose-1-1] => 0
       )
   [1]=>array(
          [package-name-2] => package2
          [package-serve-2] => Leaf
          [package-price-date-2] => 12-08-2020
          [foodType-2-2] => rice1
          [foodTags-2-2] => rice1
          [foodNotes-2-2] => dasd
          [foodchoose-2-2] => 3
          [foodType-2-3] => rice2
          [foodTags-2-3] => rice2
          [foodNotes-2-3] => qwewe
          [foodchoose-2-3] => 0
    )
)

How to solve:

You can do it through foreach() and strpos()

$newArray = [];

$k = 0;
foreach($array as $key=>$value){

    if(strpos($key,'package-name') !== false){
        $explodedkeys = explode('-',$key);
        $id = end($explodedkeys);
        $k = $id-1;
    }
    $newArray[$k][$key] = $value;
}

print_r($newArray);

Output: https://3v4l.org/5eEkA

Leave a Reply

Your email address will not be published. Required fields are marked *