Fetch data in one array if a specific data exists in another

Asked

Viewed 99 times

0

My question is this::

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 the ids will hit, ie, the ids of 1° array are all present in 2° array, but out of order and can’t sort because it comes from a randomly generated JSON.

I need to check when the ids are equal and if yes, create a new key in 1° array with the die of the field nome of 2° array.

I did

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

It doesn’t work because ids that do not match $array1['nome'] goes blank.

Is there any simple solution?

1 answer

0


If you’re sure all the id of $array1 exist in the $array2, you don’t need to check if the id is the same, just search the record for the id in $array2 and obtain 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;
}

Take 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 exit 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 on Ideone.

References:

array_search: http://php.net/manual/en/function.array-search.php

array_column: http://php.net/manual/en/function.array-column.php

  • Perfect Anderson Carlos Woss&#Xa thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.