TLDR;我的問題與PHP. Is it possible to use array_column with an array of objects不同。我只想改變數組中的鍵並保留對象,而不是像給定的答案那樣將對象的值存儲在單獨的數組中。array_column with object array
我想將對象的數組的鍵設置爲對象的值。所以這個數組:
$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
)
任何人誰知道一個乾淨的解決方案(所以沒有對或foreach循環)爲這個?
你的問題是?我展示了我當前的數組,以及我如何更喜歡它。我向你展示了我所嘗試過的以及沒有起作用的東西,如果我可能會問,那麼你需要什麼? –
@Oyeme你甚至讀過嗎?我已經提到這個鏈接,爲什麼這個答案不適合我... –