Xeen Xeen - 1 month ago 9
PHP Question

How to convert singledimensional array to multidimensional php

I have the following structure:

Array
(
[0] => product
[1] => id
[2] => name
[3] =>
[4] => type
[5] => productID
[6] => name
)


and I'd like to convert to use the empty value as a seperator, something like

[0]=>[[0][1][2]]
[1]=>[[4][5][6]]


I tried using the answer in this How to Convert a Flattened Array to Multidimensional Array in PHP post, but didn't manage to make it work.

Answer

Try this:

<?php
  $arr = array('product','id','name','','type','productID','name');
  $newArray = array();
  $i = 0;
  foreach ($arr as $key => $value) {
    if($value!=''){
      $newArray[$i][$key]= $value;
    }else{
      $i++;
    }
  }
  print_r($newArray);
?>