I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.
Related
I'm trying to follow http://woocommerce.github.io/woocommerce-rest-api-docs/?php#list-all-order-notes to get order notes from my orders and get the author and id inside a nested json respons but it's not working
Does anything stand out as being wrong here?
require_once 'auth.php';
$notes = $woocommerce->get('orders/108668/notes');
$json = json_decode($notes, true);
foreach($json as $elem) {
echo($elem['id']. ", ".$elem['author'] );
echo("<br/>");
}
If i print_r($notes); I get the response like so
Array ( [0] => stdClass Object ( [id] => 24721 [author] => haspden [date_created] => 2020-12-07T09:03:01 [date_c........
if i print_r($json); i get nothing :/
Any thouhgts? I'm sure it something obvious and due to my missunderstanding between arrays and objects with json.
Thanks
Try casting $notes with array and expose it as json using json_encode:
$notes = $woocommerce->get('orders/108668/notes');
header('Content-Type: application/json'); // this line is to make sure the output format is JSON
echo json_encode((array)$notes);
As I understand from what you supplied, the response from $notes = $woocommerce->get('orders/108668/notes'); is already an array and you can loop through it and do whatever you like. You don't need to json_decode it.
Moreover, json_decode first parameter is string as the docs says but you supplied an array.
I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.
I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));
I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);
I've outputted my array to file using the print_r($myArray, true) method, but am having trouble re-importing it as an array.
I keep returning a string with the array, not the array itself. I've tried a few different combinations including print_r and serialize, but can't seem to get it right. What am I missing?
Here's what I have:
$myArray = print_r(file_get_contents($logFile), true);
for reference the log file content looks like so:
Array
(
[0] => Array
(
[0] => blah
[1] => blah
)
...
Thanks
EDIT: Solution - Here is what I came up with:
I changed the file contents to include php tags and declared the array there using var_export instead of print_r.
Here is what I used as my content string when writing to file:
<?php $myArray = '.var_export($myArray, true).'; ?'.'>
From there it was a simple include to get the array back.
You should just store the array as ... an array, like so:
file_put_contents('myfile.txt', '<?php return ' . var_export($array, true) . '; ?>');
Then, to read:
$array = include 'myfile.txt';
See also: var_export()