phparraysmultidimensional-arrayexplode

Explode delimited string into a 2d array with a specified key in each single-element row


I have the following string: "1,3,4,7" which I need to explode into an Array in the following format:

$data = array(
   array(
      'id' => 1
   ),
   array(
      'id' => 3
   ),
   array(
      'id' => 4
   ),
   array(
      'id' => 7
   ),
);

Solution

  • You can use a combination of array_map() and explode(): First you create an array with the values and than you map all these values to the format you need in a new array.

    Something like:

    $vals = "1,3,4,7";
    
    $map = array_map(function($val) {
      return array('id' => $val);
    }, explode(',', $vals));
    
    var_dump($map);
    

    An example.