Skip to content
Advertisement

PHP Associative Array – Split comma separated value into separate array rows

I have an associative array, with some of the values in “CAT” having multiple words, separated by a comma.

I would like to split those into separate array entries (each comma separated word to create another array entry) as shown below.

I know that I can use explode() to separate those values with commas, but not sure on how to create a new array entry from it?

$categories = explode(',', $details[0]['CAT']);

Current array structure:

Array
(
    [0] => Array
        (
            [ID] => 50829
            [CAT] => "furniture,home,garden"
        )

    [1] => Array
        (
            [ID] => 50832
            [CAT] => "kids"
        )

    [2] => Array
        (
            [ID] => 50854
            [CAT] => "toys"
        )
)

Desired result:

Array
(
    [0] => Array
        (
            [ID] => 50829
            [CAT] => "furniture"
        )

    [1] => Array
        (
            [ID] => 50829
            [CAT] => "home"
        )

    [2] => Array
        (
            [ID] => 50829
            [CAT] => "garden"
        )

    [3] => Array
        (
            [ID] => 50832
            [CAT] => "kids"
        )

    [4] => Array
        (
            [ID] => 50854
            [CAT] => "toys"
        )
)

Really appreciate your help!

Advertisement

Answer

You can simply use a foreach to recreate a new array. For each category in the “CSV string”, you can add the “ID”+”new CAT” in the output array:

$array = [
    ['ID' => 50829, 'CAT' => 'furniture,home,garden'],
    ['ID' => 50832, 'CAT' => 'kids'],
    ['ID' => 50854, 'CAT' => 'toys'],
];

$out = [];                              // output array
foreach ($array as $item) {             // for each entry of the array
    $cats = explode(',', $item['CAT']); // split the categories
    foreach ($cats as $cat) {           // for each cat
        $out[] = [                      // create a new entry in output array
           'ID'  => $item['ID'],        // with same ID
           'CAT' => $cat,               // the "sub" category
        ];
    }
}

var_export(array_values($out));
array (
  0 => 
  array (
    'ID' => 50829,
    'CAT' => 'furniture',
  ),
  1 => 
  array (
    'ID' => 50829,
    'CAT' => 'home',
  ),
  2 => 
  array (
    'ID' => 50829,
    'CAT' => 'garden',
  ),
  3 => 
  array (
    'ID' => 50832,
    'CAT' => 'kids',
  ),
  4 => 
  array (
    'ID' => 50854,
    'CAT' => 'toys',
  ),
)

Or to create a same array without “CAT”:

$out = [];
foreach ($array as $item) {
    $cats = explode(',', $item['CAT']);
    unset($item['CAT']);                  // unset the original "CAT"
    foreach ($cats as $cat) {
        $out[] = $item + ['CAT' => $cat]; // copy $item and add "CAT"
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement