Rikkiebags
Rikkiebags

Reputation: 55

Explode delimited string into a 2d array with a predefined 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
   ),
);

Upvotes: 0

Views: 1496

Answers (4)

mickmackusa
mickmackusa

Reputation: 47863

Here is a thinking-outside-the-box technique that doesn't require a loop or iterated function calls.

Form a valid query string with the desired structure and parse it. The empty [] syntax will generate the indexes automatically.

Code: (Demo)

$vals = "1,3,4,7";
$queryString = 'a[][id]=' . str_replace(',', '&a[][id]=', $vals);
parse_str($queryString, $output);
var_export($output['a']);

Other approaches :

A body-less foreach: Demo

$result = [];
foreach (explode(',', $vals) as $result[]['id']);
var_export($result);

Or nominate the column key via parameter name in an array_map() callback. Demo

var_export(
    array_map(
        fn($id) => get_defined_vars(),
        explode(',', $vals)
    )
);

Output (from all above):

array (
  0 => 
  array (
    'id' => '1',
  ),
  1 => 
  array (
    'id' => '3',
  ),
  2 => 
  array (
    'id' => '4',
  ),
  3 => 
  array (
    'id' => '7',
  ),
)

Upvotes: 0

abh
abh

Reputation: 1239

<?php
$myArray=explode(",","1,3,5,7");

$result=array();
foreach($myArray as $key=>$arr)
{
    $result[$key]['id']=$arr;

}

print_r($result);
?>

Upvotes: 1

jeroen
jeroen

Reputation: 91734

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.

Upvotes: 3

KhorneHoly
KhorneHoly

Reputation: 4766

Firstly you explode the string to get the values in an array. Then you iterate through the array and set the data as array to another array

$string = "1,2,3,4";
$array = explode(",", $string);
$data = array();
foreach($array as $arr){
    $data[] = array('id' => $arr);
}

Upvotes: 0

Related Questions