'How can I set one array as a value of another array in PHP? [duplicate]
I have the following array:
Array
(
[0] => James
[1] => Mike
[2] => Liam
[3] => Shantel
[4] => Harry
)
Array
(
[0] => Green
[1] => Blue
[2] => Yellow
[3] => Purple
[4] => Red
)
How can I get these two arrays into a JSON object?
So this should be the expected output:
{"James":"Green","Mike":"Blue","Liam":"Yellow","Shantel":"Purple"}
This is what I tried doing but I'm getting a totally different output:
$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]);
}
What am I doing wrong here?
Solution 1:[1]
You want to set a specific key of $final
to a specific value. So instead of using array_push
(or $final[]
), which just adds a value to an indexed array, you want to define the key/value of the associated array $final
like:
$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];
}
Working example at https://3v4l.org/cgHtD
Solution 2:[2]
Try 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);
output:
Array
(
[James] => Green
[Mike] => Blue
[Liam] => Yellow
[Shantel] => Purple
[Harry] => Red
)
{"James":"Green","Mike":"Blue","Liam":"Yellow","Shantel":"Purple","Harry":"Red"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | WOUNDEDStevenJones |
Solution 2 | ukolaj |