moses toh
moses toh

Reputation: 13192

How can I edit json element by sub json value?

My json like this :

[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]

I have input variable $id, variable $name and variable $alt

if $id = 2, $name = 8GJE5LJGiHPC39KP20iOgy3cYQSXOllJTE7G84D2.jpeg, and $alt = test one, it will edit json that have id = 2 to be like this :

[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "8GJE5LJGiHPC39KP20iOgy3cYQSXOllJTE7G84D2.jpeg", "alt": "test one"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]

if $id = 3, $name = 33AABBCCEDC39KP20iOgy3cYQSXOllJaaBBCCE3.jpeg and $alt = test two, it will edit json that have id = 3like this :

[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "33AABBCCEDC39KP20iOgy3cYQSXOllJaaBBCCE3.png", "alt": "test two"}]

How can I do it?

Upvotes: 1

Views: 133

Answers (1)

LF-DevJourney
LF-DevJourney

Reputation: 28524

You can just find by id then change it. Check live demo here.

<?php
$array = json_decode('[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]');

$id = 2;
$name = '8GJE5LJGiHPC39KP20iOgy3cYQSXOllJTE7G84D2.jpeg';
$alt = 'test one';
foreach($array as &$v)
{
  if($v->id == $id){
    $v->alt = $alt;
    $v->name = $name;
  }
}
print_r(json_encode($array));

When you have a large array, you can use this efficient way

<?php
$array = json_decode('[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]');

$id = 2;
$name = '8GJE5LJGiHPC39KP20iOgy3cYQSXOllJTE7G84D2.jpeg';
$alt = 'test one';

$array = array_combine(array_column($array, 'id'), $array);
if(isset($array[$id]))
{
  $array[$id]->name = $name;
  $array[$id]->alt = $alt;
}
echo json_encode($array);

Upvotes: 2

Related Questions