TLDR;我的问题与PHP. Is it possible to use array_column with an array of objects不同。我只想更改数组中的键并保留对象,而不是拥有对象'存储在单独数组中的值,如给定答案。
我想将具有对象的数组的键设置为对象的值。所以这个数组:
$array = Array
(
[0] => stdClass Object
(
[id] = 12234
[value] = some value
)
[1] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
应该成为:
$array = Array
(
[12234] => stdClass Object
(
[id] = 12234
[value] = some value
)
[12994] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
现在我可以遍历数组,但我更喜欢更清洁的解决方案。我认为这应该有效:
$newArray = array_column($array, null, 'id');
唯一的问题是我有一个对象数组而不是一个数组数组,而我还没有使用PHP7。现在我在这里发现了类似的问题 PHP. Is it possible to use array_column with an array of objects
但问题是它没有回复我的预期。原因如下:
$newArray = array_map(function($o) {
return is_object($o) ? $o->id : $o['id'];
}, $array);
返回
Array
(
[0] => 12234
[1] => 12994
)
任何知道干净解决方案的人(因此没有for或foreach循环)吗?
答案 0 :(得分:5)
$array = array_combine(array_map(function ($o) { return $o->id; }, $array), $array);
这是否真的比简单的foreach
循环要好得多,除了"但是,功能编程......!" ,是值得商榷的
答案 1 :(得分:1)
// your data
$array = array(
(object) array(
"id" => "12234",
"value" => "some value",
),
(object) array(
"id" => "12235",
"value" => "some value",
),
(object) array(
"id" => "12236",
"value" => "some value",
),
);
// let's see what we have
print_r($array);
// here comes the magic ;-)
function key_flip_array($array, $keyname){
$keys = array_map(function($item, $keyname){
return (is_object($item) && isset($item->{$keyname}) ? $item->{$keyname} : (is_array($item) && isset($item[$keyname]) ? $item[$keyname] : null));
}, $array, array_fill(0, count($array), $keyname));
return array_combine($keys, $array);
}
$array = key_flip_array($array, "id");
// i hope this is what you wish to see
print_r($array);