Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

98
Vistas
Add data from second 2d array to first 2d array based on related id columns

I have two arrays $a and $b

$a = [
    '0' => [
        'name'=>'Apple',
        'id' => 1
    ],
    '1' => [
        'name'=>'Banana',
        'id' => 2
    ],
    '2' => [
        'name' => 'orange',
        'id' => 3
    ]
];

AND

$b = [
    '0' => [
        'price'=> 20,
        'a_id' => 2
    ],
    '1' => [
        'price'=> 10,
        'a_id' => 3
    ],
    '3' => [
        'price'=> 30,
        'a_id' => 1
    ]
];

I am trying to create another array with mapping with id(array $a), a_id (array $b), where my output will looks like:

$a = [
    '0' => [
        'id' => 1
        'name'=>'Apple',
        'price' => 30
    ],
    '1' => [
        'id' => 2
        'name'=>'Banana',
        'price' => 20
    ],
    '2' => [
         'id' => 3
         'name' => 'orange',
         'price' => 10
    ]
];

I have tried by array map

$combined = array_map(null,$a,$b);

But this result is not my desire result. How can I map my 1st array with 2nd array related by $a['id'] = $b['a_id']?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

This should work, also if there's no price for an item in the array $b then the default price 0 will be added.

<?php

$result = [];

$t = array_column($b, 'a_id');

foreach($a as $k => $v) {
    
    $index = array_search($v['id'], $t);
    $v['price'] = $index !== FALSE ? $b[$index]['price'] : 0;
    $result[] = $v;

}

print_r($result);

?>

Result:

(
    [0] => Array
        (
            [name] => Apple
            [id] => 1
            [price] => 30
        )

    [1] => Array
        (
            [name] => Banana
            [id] => 2
            [price] => 20
        )

    [2] => Array
        (
            [name] => orange
            [id] => 3
            [price] => 10
        )
)
over 4 years ago · Santiago Trujillo Denunciar

0

You can do it as follows:

foreach($a as $k => $item)
{        
    $price = 0;    

    foreach($b as $priceItem)
    {
       if($priceItem['a_id'] === $item['id'])
       {
            $price = $priceItem['price'];
            break;
       }   
    }

    $a[$k]['price'] = $price;
}

However, this isn't too efficient as every new price and item will exponentially increase the loops required.

If you are able to use the product IDs as the key in your first array, you could do it a lot more efficiently:

// Key $a by product ID
$a = [
    1 => [
        'name'=>'Apple',
        'id' => 1
    ],
    2 => [
        'name'=>'Banana',
        'id' => 2
    ],
    3 => [
        'name' => 'orange',
        'id' => 3
    ]
];

foreach($b as $priceItem)
{   
    $a[$priceItem['a_id']]['price'] = $priceItem['price'];
}
over 4 years ago · Santiago Trujillo Denunciar

0

You can use this code

$result = [];

for($i=0; $i<sizeof($a); $i++){
    if(array_key_exists($i,$b)){
        $b[$i]['id']=$b[$i]['a_id'];
        unset($b[$i]['a_id']);
    }
    $result[] = array_merge($a[$i], array_key_exists($i,$b)?$b[$i]:array());
}

print_r($result);
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda