1

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?

LF00
  • 27,015
  • 29
  • 156
  • 295
moses toh
  • 12,344
  • 71
  • 243
  • 443

1 Answers1

2

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);
LF00
  • 27,015
  • 29
  • 156
  • 295