I'm building an array of arrays and then calling json_encode on it.
when it returns its adding #'s to the front of the json, ie it starts ######{
removing the hashes makes it a valid json object.
controller:
multiple nested arrays are created as such
$ingredients = array();
foreach($step->ingredient as $in) {
$ingredient_data = array (
"id" => $in->id,
"name" => $in->name,
"description" => $in->description,
"link" => $in->link,
"image" => $in->image_url
);
array_push($ingredients,$ingredient_data);
}
view:
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
Related
I want to write an Array as JSON into a file. Then i want to get the content, decode it and iterate over the array. The Problem is i cannot iterate over the Array that i get from the file. What am i doing wrong?
var_dump() shows the array.
<?php
$array = array(
array("Artikel" => "Bananen",
"Menge" => 10,
"id" => "4711"
),
array("Artikel" => "Eier",
"Menge" => 1,
"id" => "abc"
)
);
file_put_contents("daten.json", json_encode($array));
$array1 = json_decode(file_get_contents("daten.json"));
var_dump($array1);
for($i=0; $i<count($array1); $i++){
echo $array1[$i]["Menge"];
echo "<br>";
}
?>
If you run your code, you will get the error Cannot use object of type stdClass as array.
This is because when json_encode is executed, the nested arrays are interpreted as an objects.
If you write:
$array1 = json_decode(file_get_contents("daten.json"), true);
then the objects will be converted to arrays and everything will work as expected.
I am trying to create the payload/data using an PHP array as input, by using [json_encode]. I noticed that the results of payload_1 has squared brackets but that payload_2 does not.
Question:
How can I create payload_2 with the result of squared brackets in the same position as in payload_1 ? To clarify, the outcome of payload_2 should be same as outcome of payload_1.
<?php
// Create payload from string.
$payload_1 = "{
\"prenumeration\":
[
{
\"url\":\"http://www.google.com\"
}
]
}";
var_dump($payload_1);
echo "\n\n";
// Create payload from array.
$payload_2 = array(
"prenumeration" => array(
"url" => "http://www.google.com"
)
);
$payload_2 = json_encode($payload_2);
var_dump($payload_2);
echo "\n\n";
Results:
Result (payload_1):
"{"prenumeration":[{"url":"http://www.google.com"}]}"
Result (payload_2):
"{"prenumeration":{"url":"http:\/\/www.google.com"}}"
Try the following:
$payload_2 = array(
"prenumeration" => array(array(
"url" => "http://www.google.com"
))
);
prenumeration must be an array of associative arrays.
array("url" => "http://www.google.com") is an associative array of one element. Associative arrays are represented with curly brackets.
array(array("url" => "http://www.google.com")) is an array of one element (that happens to be an associative array). Arrays are represented with square brackets.
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 creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format
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.