I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
So, in JavaScript I can do:
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
But I can't do:
alert(resp.errors.length);
I would like to iterate errors, that's why I'm trying to get the length. Can somebody give me a hint? Thanks!
To be able to do that, you need resp.errors to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using json_encode, the errors PHP array is "translated" to a JS object : your JSON data looks like this :
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
Instead, you would want it to look like this :
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
Notice that "errors" in an array, without named-keys.
To achieve that, your PHP code would need to be :
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
(Just remove the named-keys on errors)
Have a look at your JSON output. resp.errors will be something like this:
{"error1": {"name": "email", "value": "err1"}, ...}
As you can see, it's an object, not an array (since you passed it an associative array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
If you want it to be a JavaScript array, your PHP should look like this:
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
If you inspect the evaluated object in Firebug, you would see that "errors" is not an array but an object(associated arrays in PHP translates to object in JS). So you need to use for-in statement to iterate through an object.
You need to check every property name with hasOwnProperty to be sure that it is something you have sent, not some prototype property.
Related
Sometimes we receive input data of varying structure, for example response from online API may include some information but other not, some details are stored in complex nested arrays etc.
I like to parse this data before usage, this way I don't have to use isset() over and over later on, ex.:
$input; // source
$correct_data = arra(); // verified data
$correct_data["option-1"] = (isset($input["option-1"]) ? $input["option-1"] : "");
$correct_data["option-2"] = (isset($input["option-2"]) ? $input["option-2"] : "");
Now I can use:
my_function($correct_data["option-1"]);
my_function2($correct_data["option-2"]);
and I know that there won't be any warnings for uninitialized variables or unknown array keys.
But problem occurs for nested data e.g.
$input = array(
"settings-main" => array(
"option-1" => "val-1",
"option-2" => "val-2",
"sub-settings" => array(
"my-option" => "some val",
"my-option-2" => "some val2",
),
),
"other-settings" => array(
"other" => array(
"option-1" => "a",
"option-2" => "b",
),
),
);
It's difficult to check this on start, later I have to use something like this:
if(isset($input["settings-main"]))
{
if(isset($input["settings-main"]["option-1"]))
$input["settings-main"]["option-1"]; //do something
if(isset($input["settings-main"]["sub-settings"]))
{
if(isset($input["settings-main"]["sub-settings"]["my-option-2"]))
$input["settings-main"]["sub-settings"]["my-option-2"]; //do something
}
}
do you have any suggestions how to handle such situations without using multiple isset() instructions ?
Try this with recursive function call.
function recursive_arr($input){
foreach($input as $val){
if(is_array($val)){
recursive_arr($val);
}else{
echo $val."<br/>";
}
}
}
recursive_arr($input);
Working Example
I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);
I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);
This is my code:
$array = array(
"Birds" =>
array(
'group' => 1,
"Bird" => array(
array('id' => 1, 'img' => "img1.png", 'title' => "kate"),
array('id' => 2, 'img2' => "img2.png", 'title' => "mary")
)) );
$json = json_encode($array);
echo json_decode($json);
OUTPUT IS:
//JSON OUTPUT {"Birds":{"group":1,"Bird":[{"id":1,"img":"img1.png","title":"cardinal"},{"id":2,"img2":"img2.png","title":"bluejay"}]}}
Object of class stdClass could not be converted to string
try
var_dump($json);
This allows you to print out the details of objects and other non-primative types.
Echoing is used for strings - Your json decoded string will be an object of type stdClass
See var_dump http://php.net/manual/en/function.var-dump.php
See echo http://php.net/manual/en/function.echo.php
You have to pass the second parameter of json_decode as true, more info about these parameters at: http://php.net/manual/en/function.json-decode.php
so your echo json_decode($json); should be changed to this:
print_r(json_decode($json, true));
echo is changed to print_r since the output is an array not a string ...
Use var_dump to view variables echo converts your variable to string, while it's object. Also you can add second param to json_decode($data, true) to get array instead object, as i assume that's what you want, because input is array.
About object convertion to string you can read __toString
I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);
var_export()
var_export() gets structured
information about the given variable.
It is similar to var_dump() with one
exception: the returned representation
is valid PHP code.
serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.