skip to Main Content

Merge two arrays, the keys of the first are the values in the second

first array

    Array
    (
        [vegetables] => 2
        [fruits] => 4
    )

second array

    Array
    (
        [0] => Array
            (
                [id] => 68
                [text] => vegetables
            )
    
        [1] => Array
            (
                [id] => 60
                [text] => fruits
            )
    )

I want to get a combined array like this:

    Array
    (
        [0] => Array
            (
                [id] => 68
                [text] => vegetables
                [quantity] => 2
            )
    
        [1] => Array
            (
                [id] => 60
                [text] => fruits
                [quantity] => 4
            )
    )

I understand that this needs to be done in a loop, but how? Confused about keys and values. I’m new to PHP

2

Answers


  1. Let us name these arrays $first and $second respectively.

    The code below must add a ‘quantity’ property to each iteration of the $second array:

    <?php
    foreach ($second as $k => $v) {
        if (array_key_exists ($v['text'], $first)) {
            $second[$k]['quantity'] = $first[$v['text']];
        }
        else {
            $second[$k]['quantity'] = 0;
        }
    }
    ?>
    

    I did not debug the code, but the idea is like that.

    Login or Signup to reply.
  2. You can do this with the code:

    $first_array = [
        "vegetables" => 2,
        "fruits" => 4,
        "grains" => 1,
    ];
    
    $second_array = [
        ["id" => 68, "text" => "vegetables"],
        ["id" => 60, "text" => "fruits"],
        ["id" => 72, "text" => "breads"],
    ];
    
    $combined_array = array_map(function ($item) use ($first_array) {
        $quantity = $first_array[$item['text']] ?? 0; // Use nullish coalescing for default 0
        return array_merge($item, ['quantity' => $quantity]);
    }, $second_array);
    
    print_r($combined_array);
    

    example output:

    Array
    (
        [0] => Array
            (
                [id] => 68
                [text] => vegetables
                [quantity] => 2
            )
        [1] => Array
            (
                [id] => 60
                [text] => fruits
                [quantity] => 4
            )
        [2] => Array
            (
                [id] => 72
                [text] => breads
                [quantity] => 0
            )
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search