How to insert a new key associated with a new value at the end of a PHP Multidimensional Array

Asked

Viewed 362 times

2

I have a multidimensional array with the following structure below:

Array
(
    [0] => Array
         (
             [id] => 1877
             [type_id] => 4
             [service_id] => 1100
         )

    [1] => Array
         (
             [id] => 2299
             [type_id] => 2
             [service_id] => 1148
         )
)

Array image

I need to dynamically insert a new key associated with a value at the end of each array key to get the following structure below:

Array
(
    [0] => Array
         (
             [id] => 1877
             [type_id] => 4
             [service_id] => 1100
             [nova_chave] => "Novo Valor"  <--- 
         )

    [1] => Array
         (
             [id] => 2299
             [type_id] => 2
             [service_id] => 1148
             [nova_chave] => "Novo Valor"  <--- 
         )
)

Picture of the new array

Could someone help me how to implement this solution in PHP?

  • In order to be able to exemplify in a more complete way, can you explain to me where the data to add comes from? Will each position have a different value? These values will come from an array as it will be?

  • Vinicius Gabriel, even the data that will be inserted in the new key will come from another array.

  • This other array from which the data comes has what structure? Is there anything that can identify which value should go to which id for example? Or the order of the positions in their associative array respect the same order of the values that comes from the array?

  • The other array will also have an id, e.g.: [1] => (['id' => 2299, nova_key => 'New Value']), so you need to compare the ID’s and when they are equal take 'nova_key' => 'New Value' and add in the structure of the 1st array, you can understand?

3 answers

1

Easier than you think. Just use + with the new key and value with $arrayAssoc.

To insert the new key at the beginning:

foreach ($arrayAssoc $key => $value) { $arrayAssoc[$key] = array('nova_chave'=> "novo_valor") + $arrayAssoc[$key]; }

To insert the new key at the end:

foreach ($arrayAssoc $key => $value) { $arrayAssoc[$key] = $arrayAssoc[$key]+ array('nova_chave'=> "novo_valor"); }

0

So, in the case that exemplified the 'X' issue is the fact that in the value array there is no fixed name for the new key that will be added to your initial array.

That would be a solution:

foreach ($arrayAssociativo as $arr)
{
  foreach ($arrayValores as $arrValor)
  {
    if ($arr['id'] === $arrValor['id'])
    {
      $arr = array_merge($arr, $arrValor);
    }
  }
}

In this case for each position of its initial associative array all positions of its value array are checked. If any position has the same ID array are merged with the array_merge.

Whereas in the structure you reported that the value array will always have only two keys (id and the new key to be added), the id key will remain and the new key will be added to its value.

  • Vinicius Gabriel this proposed solution was not what I expected, it was different from what I need, the merge array is uniting one array with the other and that’s not what I need, what I need is to take only one key with its value of the second array and add in the first array. :(

  • @Jorgitodasilvapaiva then, in this scenario, the array_merge will do just that. Since your value array only has 2 keys ('id', 'chave_nova') it will add the new key in the first array. Since this new key of yours has various names, I believe this would be the most simplified solution actually, there are other ways but the code gets a little more extensive.

  • Did you happen to test that you didn’t return the expected result? If you can inform here how it ended up getting, maybe I can be wrong in some question there, then I already check and correct.

0


There are several ways to do this. I’ll leave two examples here:

First example:

<?php

    $matriz = array(
        array("id" => 1877,"type_id" => 4,"service_id" => 1100),
        array("id" => 2299,"type_id" => 2,"service_id" => 1148)
    );

    $novo_1 = 1111; 

    //Inserindo o valor dinamicamente 
    for($i=0; $i < count($matriz); $i++)
    {
        $matriz[$i]["nova_chave"] =  $novo_1;
    }

    echo "<pre>";
        print_r($matriz);
    echo "</pre>";
?>

Second Example:

<?php

    $matriz_2 = array(
        array("id" => 1877,"type_id" => 4,"service_id" => 1100),
        array("id" => 2299,"type_id" => 2,"service_id" => 1148)
    );  

    $novo_2 = ["nova_chave_2" => 2222];  

    //Inserindo a chave e o valor dinamicamente
    for($i=0; $i < count($matriz_2); $i++)
    {
        foreach($novo_2 as $key => $value)
        {
            $matriz_2[$i][$key] = $value;
        }
    }

    echo "<pre>";
        print_r($matriz_2);
    echo "</pre>";

?>

Browser other questions tagged

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