我有一個陣列:
[
(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”和“key3”屬性。
目前認為:
foreach($myArray as $key){
unset($key->key1);
}
但這不行,因為陣列還可能包含其他屬性。如果可能的話,我寧愿不使用回圈......
(對不起我的英語不好)
uj5u.com熱心網友回復:
此解決方案使用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"}]
uj5u.com熱心網友回復:
這可以通過使用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"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334766.html
