JSON 对特定对象的属性进行编码



我有一个数组:

[
(int) 0 => object(stdClass) {
key1 => 'aaa'
key2 => 'bbb'
key3 => 'ccc'
},
(int) 1 => object(stdClass) {
key1 => 'ddd'
key2 => 'eee'
key3 => 'fff'
},
(int) 2 => object(stdClass) {
key1 => 'ggg'
key2 => 'hhh'
key3 => 'iii'
}
]

我想为这个数组返回一个json_encode,但只针对"key2"one_answers";key3"属性。

For the moment that

foreach($myArray as $key){
unset($key->key1);
}

但这是不行的,因为数组可能还包含其他属性。如果可能的话,我宁愿不使用循环…

(对不起我的英语)

此解决方案使用array_map()array_intersect_key():

<?php
$data = [
['key1' => 'aaa', 'key2' => 'bbb', 'key3' => 'ccc'],
['key1' => 'ddd', 'key2' => 'eee', 'key3' => 'fff'],
['key1' => 'ggg', 'key2' => 'hhh', 'key3' => 'iii']
];
/**
* define allowed keys
*
* array_flip() exchanges the keys with their values
* so it becomes ['key2' => 0, 'key3' => 1]
* useful for array_intersect_key() later on
*
*/
$allowed = array_flip(['key2', 'key3']);
$newData = array_map(
function($item) use ($allowed) {
return array_intersect_key($item, $allowed); 
}, 
$data
);
echo json_encode($newData);

…打印:

[{"key2":"bbb","key3":"ccc"},{"key2":"eee","key3":"fff"},{"key2":"hhh","key3":"iii"}]

这可以在数组上使用array_map来完成,并且只使用您想要的属性创建一个新的对象数组。

<?php
$arr = [
['key1' => 'aaa','key2' => 'bbb','key3' => 'ccc'],
['key1' => 'ddd','key2' => 'eee','key3' => 'fff'],
['key1' => 'ggg','key2' => 'hhh','key3' => 'iii']
];
$obj = json_decode(json_encode($arr)); // to turn sample data into objects
$output = array_map(function ($e) {
$new_obj = new stdClass;
$new_obj->key2 = $e->key2;
$new_obj->key3 = $e->key3;
return $new_obj;
}, $obj);
var_dump($output);

在搜索结果

array(3) {
[0]=>
object(stdClass)#5 (2) {
["key2"]=>
string(3) "bbb"
["key3"]=>
string(3) "ccc"
}
[1]=>
object(stdClass)#6 (2) {
["key2"]=>
string(3) "eee"
["key3"]=>
string(3) "fff"
}
[2]=>
object(stdClass)#7 (2) {
["key2"]=>
string(3) "hhh"
["key3"]=>
string(3) "iii"
}
}