1

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>';
0

3 Answers 3

3

Your outer foreach loop is correct. You don't need your inner loop though as explode returns an array. Just append this array to your result array and you'll get a 2D array

$input = "13,4,3|65,1,1|27,3,2";

$result = [];

foreach (explode('|', $input) as $split)
    $result[] = explode(',', $split);

print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

2

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>';

1 Comment

Wow! So fast. Thanks so much for your answer Charlie, or is it Mac...or Deandra? Anyway, much appreciated :) It won't let me accept your answer yet, cause you answered too fast.
0

You can use the explode function to split a string with a delimiter, in this case '|', like this:

PHP:

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

$new_arrays = explode('|', $data); // with this you can separate the string in 3 arrays with the demiliter '|'

Here is the documentation of explode: http://php.net/manual/en/function.explode.php

Regards!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.