Home > Blockchain >  how to explode array in php
how to explode array in php

Time:05-25

i have data array, and this my array

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

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

in array 0 there are two ID which I separated using a comma, I want to extract the data into a new array, how to solve this?

so 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 my code

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

CodePudding user response:

The code down below should do the job. But I didn't understand why you didn't create those items seperately 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;
    }
}

CodePudding user response:

$arr = [
    array(
        'id' => '9,5',
        'item' => 'Item A, Item B'
    ),
    array(
        'id' => 3,
        'item' => 'Item C'
    )
];

$newArr = array_reduce($arr, function($tmp, $ele){
    $arrIds = explode(',', $ele['id']);
    $arrItems = explode(',', $ele['item']);
    forEach($arrIds as $key => $arrId) {
        $tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
    }
    return $tmp;
});
  • Related