phparraysmultidimensional-arraydelimited

Deconsolidate row values in a 2d array when pairs of comma-delimited values are encountered


This is my 2d array:

Array
(
    [0] => Array
        (
            [id] => 9,5
            [item] => Item A, Item B
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
)

In the first row, there are comma-separated values for id and item. I want to extract the data into individual values in a new array so that the output is like this:

Array
(
    [0] => Array
        (
            [id] => 9
            [item] => Item A
        )

    [1] => Array
        (
            [id] => 3
            [item] => Item C
        )
    [2] => Array //new array 
        (
            [id] => 5
            [item] => Item B
        )
)

This is my current code:

$arr = array();
foreach ($myarray as $val) {
    $arr[] = array(
        'id' => $val['id'],
        'item' => $val['item'],
    );
}
echo '<pre>', print_r($arr);

Solution

  • The code down below should do the job. But I didn't understand why you didn't create those items separately in the first place.

    foreach ($arr as $i => $data) {
        if (!str_contains($data['id'], ',')) continue;
    
        $items = explode(',', $data['item']);
    
        foreach(explode(',', $data['id']) as $i => $id) {
            $new = ['id' => $ids[$i], 'item' => $items[$i]];
    
            if ($i) $arr[] = $new;
            else $arr[$i] = $new;
        }
    }
    var_export($arr);
    

    Output: (Demo)

    Warning: Undefined variable $ids
    
    Warning: Trying to access array offset on null
    
    Warning: Undefined variable $ids
    
    Warning: Trying to access array offset on null
    array (
      0 => 
      array (
        'id' => NULL,
        'item' => 'Item A',
      ),
      1 => 
      array (
        'id' => 3,
        'item' => 'Item C',
      ),
      2 => 
      array (
        'id' => NULL,
        'item' => ' Item B',
      ),
    )