KeepCool KeepCool - 1 month ago 6
PHP Question

How to create a multi-dimensional array from string

Looking to create a multi-dimensional array from a string. My string is:

13,4,3|65,1,1|27,3,2

I want to store it in an array which I'm assuming would look like this:

$multi_array = array
(
array(13,4,3),
array(65,1,1),
array(27,3,2)
);


So I can call it with $multi_array[1][1], which should return "4".

Here's the code I have so far:

$string = "13,4,3|65,1,1|27,3,2";
$explode = explode("|", $string);
$multi_array = array(); //declare array

$count = 0;

foreach ($explode as $value) {

$explode2 = explode(",", $value);

foreach ($explode2 as $value2) {
// I'm stuck here....don't know what to do.
}
$count++;
}
echo '<pre>', print_r($multi_array), '</pre>';

Answer

Try this way,

$data = '13,4,3|65,1,1|27,3,2';

$return_2d_array = array_map (
  function ($_) {return explode (',', $_);},
  explode ('|', $data)
);

print '<pre>';
print_r ($return_2d_array);
print '</pre>';

OR with your own code

$string = "13,4,3|65,1,1|27,3,2";
$explode = explode("|", $string);
$multi_array = array(); //declare array

$count = 0;

foreach ($explode as $key=>$value) { // see changes on this line

  $explode2 = explode(",", $value);

  foreach ($explode2 as $value2) {
    $multi_array[$key][$count] = $value2;
    $count++; // see count variable position changes here
  }

}
echo '<pre>', print_r($multi_array), '</pre>';