Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Key Value Pairs within an Array in PHP using the json_encode() Function

Tags:

json

arrays

php

I am trying to get my JSON output in a particular syntax

here is my code:

$ss = array('1.jpg', '2.jpg');
$dates = array('eu' => '59.99', 'us' => '39.99');
$array1 = array('name' => 'game1', 'publisher' => 'ubisoft', 'screenshots' => $ss, 'dates' => $dates, 'added' => '2014/12/31');

echo json_encode($array1);

it gives me this output:

{
name: "game1",
publisher: "ubisoft",
screenshots: [
"1.jpg",
"2.jpg"
],
dates: {
eu: "59.99",
us: "39.99"
},
],
added: "2014/12/31"
}

which is CLOSE but, not exactly what I need. The dates need to be formatted slightly different. Like this:

{
name: "game1",
publisher: "ubisoft",
screenshots: [
"1.jpg",
"2.jpg"
],
dates: [
{
eu: "59.99"
},
{
us: "39.99"
}
],
added: "2014/12/31"
}

I have tried adding more dimensions to the $dates array, but that still doesn't give quite the right output. Unfortunately the php manual for the json_encode() function doesn't provide much help and there is very little documentation on more complex json encodes within php that i have found with google searching.

Any help would be greatly appreciated.

like image 897
Lee Ginger-Ninja McCarthy Avatar asked Feb 06 '26 23:02

Lee Ginger-Ninja McCarthy


1 Answers

Change the $dates assignment to:

$dates = array(array('eu' => '59.99'), array('us' => '39.99'));
like image 122
Barmar Avatar answered Feb 08 '26 12:02

Barmar