I have this code :
<?php
$array = array ( array ('pcs'=>'23', 'kg'=>'3'),
array ('pcs'=>'24', 'kg'=>'4'),
array ('pcs'=>'25', 'kg'=>'5'));
echo '<pre>';
print_r($array);
$array = json_encode($array);
echo $array;
$array = json_decode($array);
echo '<pre>';
print_r($array);
?>
and here's the output :
Array
(
[0] => Array
(
[pcs] => 23
[kg] => 3
)
[1] => Array
(
[pcs] => 24
[kg] => 4
)
[2] => Array
(
[pcs] => 25
[kg] => 5
)
)
[{"pcs":"23","kg":"3"},{"pcs":"24","kg":"4"},{"pcs":"25","kg":"5"}]
Array
(
[0] => stdClass Object
(
[pcs] => 23
[kg] => 3
)
[1] => stdClass Object
(
[pcs] => 24
[kg] => 4
)
[2] => stdClass Object
(
[pcs] => 25
[kg] => 5
)
)
why my array becomes stdClass Object? can I still manipulates stdClass Object just like an array?
UPDATE : I got this error when I tried to echo-ing $array[0]['pcs'] :
Fatal error: Cannot use object of type stdClass as array in /home/*** on line **
The "problem" has nothing in common with json_encode, but rather with json_decode.
This will return an array:
$array = json_decode($array, true);
From the PHP Manual:
json_decode() is use to Decodes a JSON string:
When you use second param as TRUE in json_decode():
Returned objects will be converted into associative arrays.
Solution for you:
$array = json_decode($array,TRUE); // use second param as TRUE in your code.
Some Basic Examples for Understanding:
Example 1:
<?php
$json = '{"test":"test","test2":"test2"}'; // json string
echo "<pre>";
print_r(json_decode($json)); // without using second param
?>
Result (return as object):
stdClass Object
(
[test] => test
[test2] => test2
)
Example 2:
<?php
$json = '{"test":"test","test2":"test2"}';
echo "<pre>";
print_r(json_decode($json,TRUE)); // with second param true
?>
Result:
Array
(
[test] => test
[test2] => test2
)
That's standard php behavior. json_decode() will convert incoming data to an array of objects of class stdClass.
You can still access all elements but you have to do it more OOP:
echo $array[0]->pcs;
echo $array[0]->kg;
If you want json_decode() to reproduce your initial array use second option of the function:
$array = json_decode($array, true);
echo $array[0]['pcs'];
echo $array[0]['kg'];
Is this Normal?
Yes, because json_decode basically returns an object and since you didn't specify the second parameter it should return an object and not an array.
According to docs
When TRUE, returned objects will be converted into associative arrays.
so to make it return an array, is to make the second parameter equal to true.
$array = json_decode($array,true);
Related
I have a object as shown below and i want to extract data from
stdClass Object
(
[day1] => stdClass Object
(
[0] => 12.06.2015
[part1] => Array
(
[0] => 19.00
[1] => 22.00
)
[part2] => Array
(
[0] =>
[1] =>
)
)
)
How will i get date as shown above with key 0. I can get others as
$string->day1->part1[0]
How can i get date "12.06.2015" ? This seems to be complicated.
JSON string for reference
{"day1":{"0":"12.06.2015","part1":["19.00","22.00"],"part2":["",""]},"day2":{"0":"13.06.2015","part1":["09.00","12.00"],"part2":["13.00","17.00"]}}
used json_decode to decode it.
You can use this:
echo $string->day1->{0};
Or my preference, decode as an array with the second argument set to true in json_decode() to use this:
echo $string['day1'][0];
I got this part in an object:
[tcd_old_value] => {"14":{"name":"Nakon radnog vremena","name_changed":false,"added_cc":[],"removed_cc":["4"]},"15":{"name":"Dodatno radno vrijeme","name_changed":false,"added_cc":[],"removed_cc":["4"]}}
after json_decode
$json_object = json_decode(tcd_old_value);
I get:
stdClass Object
(
[14] => stdClass Object
(
[name] => Nakon radnog vremena
[name_changed] =>
[added_cc] => Array
(
)
[removed_cc] => Array
(
[0] => 4
)
)
[15] => stdClass Object
(
[name] => Dodatno radno vrijeme
[name_changed] =>
[added_cc] => Array
(
)
[removed_cc] => Array
(
[0] => 4
)
)
)
I'm trying to count how many indexes are in this object (obviously the result should be 2)
$result = count($json_object);
echo $result //returns 1
Any insight on what I'm doing wrong here?
You cannot use count() in this case, because you have an object and not an array.
You may use the second parameter of json_decode() to have the JSON converted to an associative array:
$json_object = json_decode(tcd_old_value, true);
$result = count($json_object);
echo $result; // Now prints 2
Keep in mind that $json_object is no longer an object, but an array instead.
As per the document count
Returns the number of elements in array_or_countable. If the parameter
is not an array or not an object with implemented Countable interface,
1 will be returned. There is one exception, if array_or_countable is
NULL, 0 will be returned.
You may need to use
json_decode('json', true);
to convert as an array
I would like to save my count result when ElasticSearch return this line:
{"took":13,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2242,"max_score":1.0,"hits":[{"_index":"
I wish to save the total result into a variable, but I don't found the good regex rule to save "2242".
Why do you think you need a regex? Just use json_decode and access it like this; closed your JSON for this example:
$raw_json = '{"took":13,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":2242,"max_score":1.0,"hits":[{"_index":"999999"}]}}';
$decoded_json = json_decode($raw_json);
echo '<pre>';
print_r($decoded_json);
echo '</pre>';
The output would be this:
stdClass Object
(
[took] => 13
[timed_out] =>
[_shards] => stdClass Object
(
[total] => 5
[successful] => 5
[failed] => 0
)
[hits] => stdClass Object
(
[total] => 2242
[max_score] => 1
[hits] => Array
(
[0] => stdClass Object
(
[_index] => 999999
)
)
)
)
Then knowing that you just access the total under hits like this:
$hits_total = $decoded_json->hits->total;
echo $hits_total;
Or if objects are not easy for you to parse, just set json_decode to return an array by setting the second parameter to true.
$decoded_json = json_decode($raw_json, true);
And then access it like this:
$hits_total = $decoded_json['hits']['total'];
echo $hits_total;
You could use the count API facility in ElasticSearch to reduce data size for parsing.
But anyway you should use json_decode to parse returned results.
I'm having some problems getting the array in these objects. When I print_r(), the following code is printed. $message_object is the name of the object.
SimpleXMLElement Object
(
[header] => SimpleXMLElement Object
(
[responsetime] => 2012-12-22T14:10:09+00:00
)
[data] => SimpleXMLElement Object
(
[id] => Array
(
[0] => 65233
[1] => 65234
)
[account] => Array
(
[0] => 20992
[1] => 20992
)
[shortcode] => Array
(
[0] => 3255
[1] => 3255
)
[received] => Array
(
[0] => 2012-12-22T11:04:30+00:00
[1] => 2012-12-22T11:31:08+00:00
)
[from] => Array
(
[0] => 6121843347
[1] => 6121820166
)
[cnt] => Array
(
[0] => 24
[1] => 25
)
[message] => Array
(
[0] => Go tramping wellington 11-30
[1] => Go drinking Matakana 2pm
)
)
)
I'm trying to get the id arrays out of the objects with a foreach:
foreach($message_object->data->id AS $id) {
print_r($id);
}
The following reply is sent:
SimpleXMLElement Object ( [0] => 65233 ) SimpleXMLElement Object ( [0] => 65234 )
How do I get the value of [0] or am I going about this wrong? and is there a way to loop though the results and get the object keys?
I have tried to echo $id[0] but it returns no result.
When you use print_r on a SimpleXMLElement there comes magic in between. So what you see is not actually what is there. It's informative, but just not the same as with normal objects or arrays.
To answer your question how to iterate:
foreach ($message_object->data->id as $id)
{
echo $id, "\n";
}
to answer how to convert those into an array:
$ids = iterator_to_array($message_object->data->id, 0);
As this would still give you the SimpleXMLElements but you might want to have the values you can either cast each of these elements to string on use, e.g.:
echo (string) $ids[1]; # output second id 65234
or convert the whole array into strings:
$ids = array_map('strval', iterator_to_array($message_object->data->id, 0));
or alternatively into integers:
$ids = array_map('intval', iterator_to_array($message_object->data->id, 0));
You can cast the SimpleXMLElement object like so:
foreach ($message_object->data->id AS $id) {
echo (string)$id, PHP_EOL;
echo (int)$id, PHP_EOL; // should work too
// hakre told me that this will work too ;-)
echo $id, PHP_EOL;
}
Or cast the whole thing:
$ids = array_map('intval', $message_object->data->id);
print_r($ids);
Update
Okay, the array_map code just above doesn't really work because it's not strictly an array, you should apply iterator_to_array($message_object->data_id, false) first:
$ids = array_map('intval', iterator_to_array$message_object->data->id, false));
See also: #hakre's answer.
You just need to update your foreach like this:
foreach($message_object->data->id as $key => $value) {
print_r($value);
}
I need some help. I have a variable containing this string;
[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]
I need to retrieve the id and value for each pair and make it any array in PHP.
You can use json_decode and pass the second param as true so it returns an array like this
$json = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$decoded = json_decode($json,true);
print_r($decoded);
Working Example
Output would be
Array
(
[0] => Array
(
[id] => 17
[value] => 123456789
)
[1] => Array
(
[id] => 18
[value] => 2012-06-13
)
[2] => Array
(
[id] => 19
[value] => Kampala
)
[3] => Array
(
[id] => 20
[value] => 1
)
.......
)
Which you can loop through using foreach like.
foreach($decoded as $de){
// access id with $de['id']
// access value with $de['value']
}
You have got an json string. You can convert it to an array by using function json_decode
Check this code .
$str = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"}, {"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$array = json_decode($str);
foreach($array as $temp){
echo "ID : ".$temp->id."\t Value: ".$temp->value;
echo "<br />";
}