KeepCool
KeepCool

Reputation: 565

How to create an array of indexed arrays from a string with two sets of delimiters

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

Upvotes: 1

Views: 884

Answers (3)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

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

Upvotes: 2

Radames E. Hernandez
Radames E. Hernandez

Reputation: 4425

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!

Upvotes: 0

Ayush
Ayush

Reputation: 42450

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

Upvotes: 3

Related Questions