Home > Software engineering >  How to add data inside an array with another array in PHP
How to add data inside an array with another array in PHP

Time:05-03

I have this data

string(94) "[{"value":"Charger"},{"value":"Bag Only"},{"value":"Data Privacy Filter"},{"value":"Headset"}]"

now I have set an array like this

$accessoriesID = array ("Charger" => "11043" , 
"Mouse" => "11044", 
"Bag With Strap" => "11045", 
"Bag Only" => "11046",
"Cable Lock" => "11047",
"Data Privacy Filter" => "11048",
"Numeric Lock" => "11049",
"Headset" => "11050",
"HDMI to VGA adapter" => "11051",
"LAN Adapter" => "12223",
"Others (Please include in the remarks box below.)" => "11052"
);

now here's my code

foreach($_POST['Acc'] as $accessories)
{
   $arrAccesories[]['value'] = $accessories;    
}

var_dump(json_encode($arrAccesories));    

what I am trying to achieve is to merge the 2 arrays with the same value so the expected output should be like this

string(94) "[{"value":"Charger", "id": "11043"},{"value":"Bag Only", "id": "11046"},{"value":"Data Privacy Filter", "id": "11048"},{"value":"Headset", "id": "11050"}]"

I just want some guidance on how to achieve this or reference so I can learn to do these things.

CodePudding user response:

you can use normal for loop:

$arrAccesories = '[{"value":"Charger"},{"value":"Bag Only"},{"value":"Data Privacy Filter"},{"value":"Headset"}]';
$arrAccesories = json_decode($arrAccesories, true);

$accessoriesID = array ("Charger" => "11043", 
"Mouse" => "11044", 
"Bag With Strap" => "11045", 
"Bag Only" => "11046",
"Cable Lock" => "11047",
"Data Privacy Filter" => "11048",
"Numeric Lock" => "11049",
"Headset" => "11050",
"HDMI to VGA adapter" => "11051",
"LAN Adapter" => "12223",
"Others (Please include in the remarks box below.)" => "11052"
);

for ($i=0; $i < count($arrAccesories); $i  ) {
  $value = $arrAccesories[$i]['value'];
  if (isset($accessoriesID[$value])) {
    $arrAccesories[$i]['id'] = $accessoriesID[$value];
  }
}

var_dump(json_encode($arrAccesories));
  • Related