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.
Related
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 have a multidimensional array and would like to call the key and the value separately, of individual levels inside the array.
Now with a normal array, I can do this by writing:
$example = array('one', 'two', 'three');
echo $example[0];
and this will return: one
However, when I try to do this with a multidimensional array like so:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
echo $example[0];
echo $example[0][0];
Instead of echoing 'optionone' followed by 'one' I get nothing returned, and no error code.
When trying to see why this is happening by using:
var_dump($example[0)];
or
var_dump($example[0][0]);
NULL is returned.
I would really appreciate if someone could tell me how to correctly get/echo/call 'optionone' to return from the array as a string: 'optionone' without writing the name and how can I call the value 'one' without writing:
$example['optionone'][0];
I'm trying to create something where it doesn't know the key name, so it rather is going by the position of the keys but i would like to be able to return the key names at different points in the program but I can't seem to figure out how to do this.
This should work for you:
Just get your associative keys into an array with array_keys(), so you can access them as a 0-based indexed array, e.g.
So with array_keys($example) you end up with the following array:
Array
(
[0] => optionone
[1] => optiontwo
[2] => optionthree
)
Which you then can access as you want it:
<?php
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
$keys = array_keys($example);
echo $keys[0] . "<br>";
echo $example[$keys[0]][0];
?>
output:
optionone
one
The outer array in your example is an associative array. There is not value at index 0. If you need to get to to the first key in the associative array without knowing the name of the key you would need to do something like:
$example = array(
'optionone' => array('one', 'two', 'three'),
'optiontwo' => array('a','b','c'),
'optionthree' => array(1,2,3)
);
//get array keys into array
$example_keys = array_keys($example);
// get value at first key in $example array
$first_inner_array = $example[$example_keys[0]];
// get first value from first inner array
$first_value = $first_inner_array[0];
// Or to get an arbitrary value:
$x = ... // whatever inner array you want to get into
$y = ... // whatever index within inner array you want to get to
$value = $example[$example+keys[$x]][$y];
I would say that if you find yourself doing this in code, you probably have your data structured poorly. Associative arrays are not meant to convey any sort of element ordering. For example, if you changed your example array to this:
$example = array(
'optiontwo' => array('a','b','c'),
'optionone' => array('one', 'two', 'three'),
'optionthree' => array(1,2,3)
);
You would get a different value retrieved from above code even though the relationship between outer array keys and inner array contents has not been changed.
not tested
foreach($example as $f_array){
foreach($f_array as $key => $val){ //iterate over each array inside first array
echo $key; //should print 'optionone'
echo $val[0]; //should print 'one'
break;
}
}
I have this data:
Array
(
[id] => 19936953
[name] => Zackaze
[profileIconId] => 585
[summonerLevel] => 30
[revisionDate] => 1394975422000
)
$str = json_decode($data,true);
$row = (object) $str;
echo $row['name'];
I tried this code but it constantly gives this error:
Fatal error: Cannot use object of type stdClass as array
Hopefully you can help me.
While the conversion to an object is unnecessary (as others have mentioned), that is not the cause of your error. You cannot access object properties using $array['key'] notation. You must use $object->property.
Alternatively, you can remove the $row = (object) $str; line, and then you can access $row as an array.
You already have decoded your json as an associative array since you used true as second parameter so you can print it directly with scopes. If you need to decode as an object simply remove the second parameter, I think you will need to access it in another way though.
$str = json_decode($data,true);
echo $str['name'];
The second argument of json_decode will convert the Object into a Associative Array. Just remove the second argument or change it to false and it will return a stdClass instead of a Associative array.
You can see the Documentation.
Try outputting like
$str = json_decode($data,true);
$str = array
(
'id' => 19936953,
'name' => Zackaze,
'profileIconId' => 585,
'summonerLevel' => 30,
'revisionDate' => 1394975422000
);
$row = (object) $str;
echo $row->name;
Or a cleaner way
$str = json_decode($data);
echo $str->name;
How can I use php json_encode to produce the following from an array?
{"issue":{"project_id":"Test Project","subject":"Test Issue"}}
I've been trying for the last 40 mins but I can't get it working for the life of me.
The best I can do is:
$arr = array ("project_id"=>"Baas","subject"=>"Test Issue");
echo json_encode($arr); // {"project_id":"Baas","subject":"Test Issue"}
The problem is making "issue" parent. Any hint on how to accomplish this?
Thanks!
The output you want is essentially an associative array nested in another associative array. So, create that data structure, then encode it.
$child_arr = array("project_id" => "Baas", "subject" => "Test Issue");
$parent_arr = array("issue" => $child_arr);
echo json_encode($parent_arr);
Or, if we're in a one-liner mood today:
$arr = array("issue" => array("project_id" => "Baas", "subject" => "Test Issue"));
echo json_encode($arr);
$arr = array ("issue" => array("project_id"=>"Baas","subject"=>"Test Issue"));