如何在 PHP 中更新 Json 对象中的项


How to update an item in a Json object in PHP

我有一个这样的json对象:

  {
        "fields" : 
        [
            {
              "name" : "news_title",
              "type" : "text",
              "value" : "old title"
            },
            {
              "name" : "news_content",
              "type" : "textarea",
              "value" : "old content"
            }
        ]            
  }

我有一个表格,只给我带来这些字段的值:

Array
(
    [news_title] => My new title
    [news_content] => My new content
    [other_values_doesnt_mach_json_file] => always comes at the end of the array
)

我的目标是使用新值更新该 json 对象.. 所以我得到带有新值的 json 对象,如下所示:

  {
        "fields" : 
        [
            {
              "name" : "news_title",
              "type" : "text",
              "value" : "My new title"
            },
            {
              "name" : "news_content",
              "type" : "textarea",
              "value" : "My new content"
            }
        ]            
  }

在这里我可以遍历 Json 对象..

$source = json_decode($oldjson);
foreach($source->fields as $field){
        echo $field->name .' - '. $field->value .' <br />';
        //$field->value =  'test'; Here I'm trying to update the values of each field with the new data ..
}

在这里,我如何遍历我的新值数组..

    // laravel post 
foreach(Input::get() as $name => $value){
    echo $name .' : '. $value .' <br /> ' ;
}

但是我不知道如何将这些拖曳组合在一起以获得具有新值的新 json 对象。

提前感谢您的帮助

$source = json_decode($oldjson);
$input = Input::get();
foreach($source->fields as $i => $field) {
  echo $field->name .' - '. $field->value .' <br />';
  if (isset($input[$field->name])) {
    $field->value = $input[$field->name];
    //$source[$i] = $field; no need for this line, at least for my main issue above 
  }
}

这有效:

$json = '{"fields":[{"name":"news_title","type":"text","value":"old title"},{"name":"news_content","type":"textarea","value":"old content"}]}';
var_dump($json);
$oJson = json_decode($json) ;
$data = array(
    'news_title' => 'My new title',
    'news_content' => 'My new content',
    'other_values_doesnt_mach_json_file' => 'always comes at the end of the array',
);
foreach ( $data as $key => $val ) {
    foreach ( $oJson->fields as $i => $oVal ) {
        if ( isset($oVal->name) && $oVal->name == $key ) {
            $oJson->fields[$i]->value = $val;
        }
    }
}
$json = json_encode($oJson) ;
var_dump($json);

您可以使用额外的计数器并同时开始跟踪输入数组和 json,如下所示:

$count = 0;
foreach(Input::get() as $name => $value){
   echo $name .' : '. $value .' <br /> ' ;
   $source->fields[$count]->name = $name;
   $source->fields[$count]->value = $value;
}