skip to Main Content

below is my array output.
I want to divide the data into multiple arrays or into multidimensional arrays.

Array(
    [cuisineId] => Array
        (
            [0] => 1
            [1] => 2
        )

    [dishId] => Array
        (
            [0] => 90
            [1] => 525
        )

    [quantity] => Array
        (
            [0] => 1
            [1] => 2
        )

    [price] => Array
        (
            [0] => 200
            [1] => 440
        )

)

So what can I do to get the below data from the above array?

array(
    "cuisineId" : 1,
    "dishId" : 90,
    "quantity" : 1,
    "price" : 200
)
array(
    "cuisineId" : 2,
    "dishId" : 525,
    "quantity" : 2,
    "price" : 440
)

2

Answers


  1. Provided that the arrays are always of equal length, you can loop over them like so:

    for ($i = 0; $i < count($data['cuisineId']); $i++)
    {
        $entry = [
            'cuisineId' => $data['cuisineId'][$i],
            'dishId' => $data['dishId'][$i],
            'quantity' => $data['quantity'][$i],
            'price' => $data['price'][$i]
        ];
    
        $output[] = $entry;
    }
    
    Login or Signup to reply.
  2. Here is a way to do it:

    function extractNum($arr, $num)
    {
        return array_map(fn($a) => $a[$num], $arr);
    }
    
    $arr = ['cuisineId' => [1, 2], 'dishId' => [90, 525], 'quantity' => [1, 2], 'price' => [200, 440]];
    $arr0 = extractNum($arr, 0);
    $arr1 = extractNum($arr, 1);
    
    print_r($arr0);
    print_r($arr1);
    

    Output:

    Array
    (
        [cuisineId] => 1
        [dishId] => 90
        [quantity] => 1
        [price] => 200
    )
    Array
    (
        [cuisineId] => 2
        [dishId] => 525
        [quantity] => 2
        [price] => 440
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search