我有以下陣列:
Array
(
[0] => James
[1] => Mike
[2] => Liam
[3] => Shantel
[4] => Harry
)
Array
(
[0] => Green
[1] => Blue
[2] => Yellow
[3] => Purple
[4] => Red
)
如何將這兩個陣列放入 JSON 物件?
所以這應該是預期的輸出:
{"James":"Green","Mike":"Blue","Liam":"Yellow","Shantel":"Purple"}
這是我嘗試做的,但我得到了完全不同的輸出:
$final = array();
$names = ['James', 'Mike', 'Liam', 'Shantel', 'Harry']
$colors = ['Green', 'Blue', 'Yellow', 'Purple', 'Red']
for ($i = 0; $i <= 4; $i ) {
$final[] = array_push($final, $names[$i], $colors[$i]);
}
我在這里做錯了什么?
uj5u.com熱心網友回復:
您想將特定鍵設定為$final特定值。因此,您不想使用array_push(或$final[]),它只是向索引陣列添加一個值,而是要定義關聯陣列的鍵/值,$final例如:
$final[$names[$i]] = $colors[$i];
$final = array();
$names = ['James', 'Mike', 'Liam', 'Shantel', 'Harry'];
$colors = ['Green', 'Blue', 'Yellow', 'Purple', 'Red'];
foreach($names as $i => $key) {
$final[$key] = $colors[$i];
}
https://3v4l.org/cgHtD上的作業示例
uj5u.com熱心網友回復:
嘗試array_combine()
$a = ["James", "Mike", "Liam", "Shantel", "Harry"];
$b = ["Green", "Blue", "Yellow", "Purple", "Red"];
$c = array_combine($a, $b);
print_r($c);
echo json_encode($c);
輸出:
Array
(
[James] => Green
[Mike] => Blue
[Liam] => Yellow
[Shantel] => Purple
[Harry] => Red
)
{"James":"Green","Mike":"Blue","Liam":"Yellow","Shantel":"Purple","Harry":"Red"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473523.html
上一篇:我怎樣才能旋轉這個陣列?
