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

时间:2014-11-28 07:31:57

标签: php arrays json

我有一个像这样的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对象。

提前感谢您的帮助

3 个答案:

答案 0 :(得分:1)

$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 
  }
}

答案 1 :(得分:1)

这有效:

$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);

答案 2 :(得分:0)

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

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