Accessing JSON encoded PHP Array in jQuery - php

I have an PHP Array which is formatted in the following format :
$jsonArray = array(
"facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
"twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);
I've then done the following so I can access the array
echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";
And to access the array I tried the following
alert(window.MyArray['facebook'][0]['user']);
yet that's seemed to fail, any directions?

window.MyArray['facebook'][0]['user']
--------------------------^^^
Why do you need [0] here?
Use this:
window.MyArray['facebook']['user']
MyArray gives this:
{
"facebook": {
"user": "8",
"user_id": "10",
"user_post": "6"
},
"twitter": {
...
}
}
MyArray['facebook'] results in the following array:
{
"user": "8",
"user_id": "10",
"user_post": "6"
}
Therefore, MyArray['facebook']['user'] results in 8.

try this way:
alert(window.MyArray.facebook.user);
it will work

You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Related

Make a JSON file with multiple same format using PHP

Fist of all i would like to tell I am a beginner for JSON. I would like to know how to make a following format JSON using PHP. I think I want to use loop function.
Example:
[ { "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" } ]
In my PHP file have $VALUE variable in different places. I want know id and name values store method to make this JSON. I can not use $VALUE1, $VALUE2 etc.
Some places have following $VALUE variable with some data. is it method right to make this JSON
$VALUE = array("id" => "1", "name" => "test1");
$VALUE = array("id" => "3", "name" => "test3");
I think that json_encode() and json_decode() will help you.
$array = [
["id" => 1, "name" => "test1"],
["id" => 2, "name" => "test2"],
["id" => 3, "name" => "test3"],
["id" => 4, "name" => "test4"]
];
$jsonEncoded = json_encode($array);
$jsonDecoded = json_decode($jsonEncoded);
var_dump("Json Encoded array to string:", $jsonEncoded);
var_dump("Json Decoded string to array:", $jsonDecoded);
In order to update (add/update or remove) the encoded json array you need to decode first and encode again. There is no other way to add an "object" to an already encoded json string.
You can always check the official documentation for more information.
json_encode
json_decode
You can do it like this if you wanted : using arrays and with cast to an object
$json_php_oupout = [
(object)["id"=>"1", "name"=>"test1"],
(object)["id"=>"2", "name"=>"test2"],
(object)["id"=>"3", "name"=>"test3"],
(object)["id"=>"4", "name"=>"test4"],
(object)["id"=>"5", "name"=>"test5"]
];
var_dump($json_php_oupout);
if you want VALUE as an array to it like this adding manually indexes or with a loops.
$VALUE[0] = (object)array("id" => "1", "name" => "test1");
$VALUE[1] = (object)array("id" => "3", "name" => "test3");

Best Practice To Convert Regular Array To Associative Using An Attribute as a Key?

Let's say I have the following array
[
{
"id": "16",
"name": "dog",
},
{
"id": "17",
"name": "cat",
},
{
"id": "18",
"name": "mouse",
}
]
I want to use a specific attribute, id as the key for the array. I could do this:
$someArray = [
["id" => "16", "name" => "dog"],
["id" => "17", "name" => "cat"],
["id" => "18", "name" => "mouse"]
];
$newArray = [];
foreach ($someArray as $currItem)
{
$newArray[$currItem["id"]] = $currItem;
}
Then I would have this (the desired outcome)
{
"16": {
"id": "16",
"name": "dog"
},
"17": {
"id": "17",
"name": "cat"
},
"18": {
"id": "18",
"name": "mouse"
}
}
My question is: is there a better way to do this? Do I really have to loop through every item just to redefine my array ever so slightly?
I seem to have found a solution using information from Rizier123's comment and this thread: PHP Change Array Keys
As far as I can tell array_column is only going to give me an array of ids, so I need to use it with array_combine and array_values. Please don't be afraid to post if you have a better answer
$someArray = [
["id" => "16", "name" => "a"],
["id" => "17", "name" => "b"],
["id" => "18", "name" => "c"]
];
$newArray = array_combine(array_column($someArray, "id"), $someArray);
You beat me to the answer but I might contribute a little anyway...
I'm not sure where your original array is coming from, but if you are decoding JSON, then you can provide a second param to force objects to be converted to associative arrays
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents, TRUE); // note the second parameter
$v = array_combine(array_column($arr, "id"), $arr);
var_dump($v);
EDIT:
If you can tolerate your output array having objects, this might also work:
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
array_column(
array_map(
function($item) { return (array)$item; },
$arr
),
"id"
),
$arr
);
var_dump($v);
Keep in mind though that performance could become a concern for very very large arrays. This is doing a lot of array munging.

print foreach loop with json_encode in php

I am new to php. so it may be very basic but I don't know it. So, I want to output like this in php using json_encode().
"option": [
{
"poOptionGroup": "11",
"optGrpID": "11",
"optGrpName": "Choose Backing Material"
},
{
"optID": "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
},
{
"optID": "41",
"optName": "Clear (Plexiglass)",
"optPriceDiff": "18"
},
{
"optID": "218",
"optName": "Neon Stand Off",
"optPriceDiff": "18"
},
{
"optID": "219",
"optName": "White Plastic",
"optPriceDiff": "18"
}
],
"option": [
{
"poOptionGroup": "13",
"optGrpID": "13",
"optGrpName": "Any notes you want to include with your order"
},
{
"optID": "174",
"optName": "NO Thanks",
"optPriceDiff": "0"
},
{
"optID": "175",
"optName": "YES OUTDOOR",
"optPriceDiff": "170"
}
],
"SPIN3": [
{
"poOptionGroup": "56",
"optGrpID": "56",
"optGrpName": "Upgrade to OUTDOOR"
},
{
"optID": "44",
"optName": "",
"optPriceDiff": "20.02"
}
]
for this I have two nested foreach loop. which is as below:
$product=array();
foreach($query as $q){
$product['optGrpID']= $q['optGrpID'];
$product['optGrpName'] = $q['optGrpName'];
$product['poOptionGroup'] = $q['poOptionGroup'];
$opt_id=$product['optGrpID'];
$string= sql("select optID, optName, optPriceDiff from options where optGroup='$opt_id' ");
foreach ($string as $k=>$s){
$product['options']['optID']=$s['optID'];
$product['options']['optName']=$s['optName'];
$product['options']['optPriceDiff']=$s['optPriceDiff'];
}
}
so how can I achieve this desired output? please help. any help will be appreciate.
I am right in the proces of writing a PHP JSON API so I came across similar problems in the past few days. While I can't / don't want to solve your particular question about the PHP code, here is the most important thing I learned that I didn't find in many documentations or tutorials:
Giving json_encode() an associative array produces an JSON object with {key: value, key: value, ...}. Giving it a non-associative array produces a JSON list with [value, value, value, ...]. The values in the latter version can off course be objects them self ({...}). This means to get the structure you want, you have to pass the following array to json_encode:
array(
"option" => array(
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
array(
"optId" => "40",
"optName": "Black (Plexiglass)",
"optPriceDiff": "0"
),
.......
),
"SPIN3" => array(
array(
"poOptionGroup" => "56",
"optGrpID" => "56",
"optGrpName" => "Upgrade to OUTDOOR"
),
array(
"optID" => "44",
"optName" => "",
"optPriceDiff" => "20.0"
)
)
);
As you can see, some of those arrays are associative arrays, some of them are non-associative arrays acting as a "simple list". Knowing this, it should be easy to modify your PHP code to produce an array like the above and pass it to json_encode(). Unless you force json_encode() to allways produce JSON objects with a flag, PHP handles the conversion to JSON objects and JSON lists as seen above.
For correct terminology: "list" refers to JSON arrays, whereas associative arrays are converted to JSON objects with string-value-links. See the JSON website for details.

Return an Array instead of Object

I am fetching data from DB like this
$endResult = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
if (!isset($endResult[$row['car']])) {
$endResult[$row['car']]= (object) array(
'car' => $row['car'],
'carModel' => $row['carModel'],
'colors' => array()
);
}
$endResult[$row['car']] -> colors [] = (object) array(
'paintedOn' => $row['paintenOnDate'],
'paintedBy' => $row['paintedBy']
);
}
//return with slim.php
$response->body(json_encode($endResult));
and result I am getting
{"1":
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}]
},
"2":{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}]
}
}//<--replace this with []
Even if $endResult is declared as Array I am getting {} brackets, how could I replace "Object" brackets with "Array" brackets?
UPDATE: I can't remove json_encode as the front-end (backbone) expecting collection
UPDATE 2: $endResult = array(); return [...]
but this $endResult[$row['car']]= (object) array(...) convert it to {...}
You can't achieve what you want because it would result in invalid JSON. According to json.org:
An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
So you can only have values in an array. Because you are adding a name to the value, it must become an object.
If you really want your JSON to be wrapped in an array you need to remove the first-level names, in your example "1" and "2":
[
{
"car": "1",
"carModel": "model-1",
"colors": [
{
"paintedOn": "2014-11-07",
"paintedBy": "5"
},
{
"paintedOn": "2014-11-08",
"paintedBy": "6"
}
]
},
{
"car": "2",
"carModel": "model-2",
"colors": [
{
"paintedOn": "2014-11-09",
"paintedBy": "7"
},
{
"paintedOn": "2014-11-10",
"paintedBy": "8"
}
]
}
]
Remove the conversion to JSON. Also "declaration" in PHP doesn't matter. You can still assign different types in the course of your program.
I think the PHP function json_decode Should help you here. This turns the JSON format into an array.
use json_decode($data,true) for convert returned data in to array.
simply use array_values function:
$array = array_values($response);

Add new key/value pair into JSON in PHP

I have a result from my MySQL DB that I'm json encoding in PHP, the result looks like
:
[
{
"id": "8488",
"name": "Tenby",
"area": "Area1"
},
{
"id": "8489",
"name": "Harbour",
"area": "Area1"
},
{
"id": "8490",
"name": "Mobius",
"area": "Area1"
}
]
What I would like to do is to add a new key/value pair to that JSON so that it will be :
[
{
"id": "8488",
"name": "Tenby",
"area": "Area1",
"image": "1278.jpg"
},
{
"id": "8489",
"name": "Harbour",
"area": "Area1",
"image": "1279.jpg"
},
{
"id": "8490",
"name": "Mobius",
"area": "Area1",
"image": "1280.jpg"
}
]
So how can I do that in PHP?
<?php
$data[0]['id']="8488";
$data[0]['name']="Tenby";
$data[0]['area']="Area1";
$data[1]['id']="8489";
$data[1]['name']="Harbour";
$data[1]['area']="Area1";
$data[2]['id']="8490";
$data[2]['name']="Mobius";
$data[2]['area']="Area1";
echo json_encode($data)."<br/>";
/*Add Image element (or whatever) into the array according to your needs*/
$data[0]['image']="1278.jpg";
$data[1]['image']="1279.jpg";
$data[2]['image']="1280.jpg";
echo json_encode($data);
?>
PHP is not very good with JSON. Its best to convert from JSON to Array to do this - what #egig has also recommended.
Example code:
$temp = json_decode($json);
$temp[] = new data, whatever you want to add...;
$json = json_encode($temp);
Hope this helps.
hu?
the result of the db query will be an array or an object...
add the additional entry to that data, only encode after every necessary data manipulation is done
alternatives, but clumsy (horrible):
json_decode, add stuff, json_encode
build your additional data as a string, str_replace for example "area": "Area1" in your json string with "area": "Area1", "image": "1278.jpg"
but really:
output formatting like json_encode should only be done once you are sure that you have the whole output together and it is send out
Maybe things have changed since then, but I know this will work at this current stage:-
So here is the JSON string:-
$strJSON = '[
{
"id": "8488",
"name": "Tenby",
"area": "Area1"
},
{
"id": "8489",
"name": "Harbour",
"area": "Area1"
},
{
"id": "8490",
"name": "Mobius",
"area": "Area1"
}
]';
If this is still a string, then I would convert it into an object like this:-
$json = json_decode( $strJSON );
Now that it is in object format, to add my "image" keys with their values, I would then add them like it is shown below:-
$json[0]->image = "1278.jpg";
$json[1]->image = "1279.jpg";
$json[2]->image = "1280.jpg";
So then if I add the code below after the above code:-
echo "<pre>";
print_r( $json );
echo "</pre>";
We should then see it outputting on the page like so:-
Array
(
[0] => stdClass Object
(
[id] => 8488
[name] => Tenby
[area] => Area1
[image] => 1278.jpg
)
[1] => stdClass Object
(
[id] => 8489
[name] => Harbour
[area] => Area1
[image] => 1279.jpg
)
[2] => stdClass Object
(
[id] => 8490
[name] => Mobius
[area] => Area1
[image] => 1280.jpg
)
)
//$index = some value in array;
for($i=0;$i<count($index);$i++){
$data[$i]->key = $index[$i];
}
print $data;

Categories