如何通过sub json值编辑json元素?

时间:2017-05-25 07:15:59

标签: php json string

我的json喜欢这样:

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

我输入变量$id,变量$name和变量$alt

如果$id = 2$name = 8GJE5LJGiHPC39KP20iOgy3cYQSXOllJTE7G84D2.jpeg$alt = test one,它会编辑id = 2的json,如下所示:

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

如果$id = 3$name = 33AABBCCEDC39KP20iOgy3cYQSXOllJaaBBCCE3.jpeg$alt = test two,它会编辑id = 3这样的json:

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

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您可以通过ID找到然后更改它。现场检查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));

如果您拥有大型数组,则可以使用此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);