Find data in an array if a specific data exists in another

0

My question is:

I have 2 arrays :

teste [
        id: 20,
        campo: nada
        etc, 
        id: 30,
        campo: nada
        etc, 
]

teste 2 [
        id: 12, 
        nome: maria, 
        etc,
        id: 30, 
        nome: joão, 
        etc,
]

All ids will hit, that is, the ids of the 1st array are all present in the 2nd array , however out of order and not you can sort because this comes from a randomly generated JSON.

I need to check when ids are the same, and if so, create a new key in the 1st array with the field data nome of the 2nd array .

I did

foreach ($array1 as $teste) {
    if($teste['id']==$array2['id']) {
        $array1['nome'] = $array2['nome'];
    }
}

It does not work, since the ids that does not hit $array1['nome'] is left blank.

Is there a simple solution?

    
asked by anonymous 05.05.2017 / 20:10

1 answer

0

If you are sure that all id $array1 exists in $array2 , you do not need to check that id is equal, just look for the id $array2 and get the value of nome :

foreach ($array1 as $i => $teste) {
    // Retorna a posição em $array2 onde se encontra o id:
    $index = array_search($teste["id"], array_column($array2, "id"));

    // Obtém o nome:
    $name = $array2[$index]["nome"];

    // Define o nome no $array1:
    $array1[$i]["nome"] = $name;
}

See an example:

$array1 = [
  ["id" => 1, "campo" => "nada 1"], 
  ["id" => 2, "campo" => "nada 2"],
  ["id" => 3, "campo" => "nada 3"]
];

$array2 = [
  ["id" => 2, "nome" => "Nome 2"], 
  ["id" => 3, "nome" => "Nome 3"],
  ["id" => 1, "nome" => "NOme 1"]
];

foreach ($array1 as $i => $teste) {
    // Retorna a posição em $array2 onde se encontra o id:
    $index = array_search($teste["id"], array_column($array2, "id"));

    // Obtém o nome:
    $name = $array2[$index]["nome"];

    // Define o nome no $array1:
    $array1[$i]["nome"] = $name;
}

var_export($array1);

The output is:

array (
  0 => 
  array (
    'id' => 1,
    'campo' => 'nada 1',
    'nome' => 'NOme 1',
  ),
  1 => 
  array (
    'id' => 2,
    'campo' => 'nada 2',
    'nome' => 'Nome 2',
  ),
  2 => 
  array (
    'id' => 3,
    'campo' => 'nada 3',
    'nome' => 'Nome 3',
  ),
) 
  

See working at Ideone .

References :

array_search : link

array_column : link

    
05.05.2017 / 20:29