Search code examples
phparraysstringmultidimensional-arrayexplode

Explode each string in a flat array


I have an array from a post operation

$country = $_POST['country']; //The number of countries differ according to the user selection
$c = count($country);

Output: `

Array ( [0] => England,69,93 [1] => Australia,79,84 [2] => Greece,89,73 [3] => Germany,59,73 )`

I will have to break it into a multidimensional array like:

> Array ( [0] => Array ( [0] => England [1] => 69 [2] => 93)
>         [1] => Array ( [0] => Australia [1] => 79 [2] => 84)                      
>         [2] => Array ( [0] => Greece [1] => 89 [2] => 73)
>         [3] => Array ( [0] => Germany [1] => 59 [2] => 73))

How do I do this in PHP

I tried

$r = array();

foreach($country as &$r){
  $r = explode(",", $r);
  //for($i = 0; $i < count($country); $i++){
    //for($j = 0; $j < count($r); $j++){
        //$array[$i][$j] = $r;
    //}
  //}
}
echo '<br>';
print_r($r);

The for-loop also did not work and hence commented it out but left it as a an option if needed.

The print function now only prints 1 of the array. Not exactly sure what have I done wrong. Any help is appreciated. Thank you


Solution

  • You were nearly there:

    $r = array();
    
    foreach($country as $country_item){
      $r[] = explode(",", $country_item);
    }
    echo '<br>';
    print_r($r);
    

    The above should work.

    What might be even better for you (if your country is unique in each array):

    $r = array();
    
    foreach($country as $country_item){
      $temp_array = explode(",", $country_item);
      $r[$temp_array[0]] = array($temp_array[1], $temp_array[2]); 
    }
    echo '<br>';
    print_r($r);
    

    This will give you an output like follows:

    > Array ( [England] => Array ( [0] => 69 [1] => 93)
    >         [Australia] => Array ( [0] => 79 [1] => 84)                      
    >         [Greece] => Array ( [0] => 89 [1] => 73)
    >         [Germany] => Array ( [0] => 59 [1] => 73))
    

    This therefore means you can access a countries figures as follows:

    $r[$country_name];