如何使用PHP从JSON字符串中删除属性

时间:2012-02-09 23:58:31

标签: php json

我在PHP中有一个JSON结果,如下所示:

[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},

{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},

{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]

我想删除属性(包含Type和URL),以便JSON结果被展平。所以我希望它看起来更像:

[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]

PHP中消除每个属性实例的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

使用json_decode()array_map()json_encode()应该很容易:

function strip_arguments( $item){
  $new_result = array(
    'Id' => $item['Id'],
    'Name' => $item['Name'],
  )
  return $new_result;
}

$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);

您当然可以在strip_arguments内使用unset()(而不是创建新数组),但这样可以确保任何“新属性”都不会成为低谷。

您可以使用return array(...)而不是将变量和链操作声明为:json_encode(array_map( 'strip_arguments', json_decode( $input)));:)

答案 1 :(得分:2)

//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);

答案 2 :(得分:0)

使用PHP的JSON工具,您可以将JSON字符串转换为数组,从这里使用简单的foreach语句和REGEX来删除数组条目。

完成此操作后,只需使用PHP函数转换回JSON字符串,并随意使用它: - )

我想到的功能是--json_decode,json_encode。

由于 安德鲁