Print value from stdClass Object/array with curly brackets - php

Using PHP, I printed out an array ($result) using print_r. But the format in which the array has been returned is a new one on me. Specifically, how do I retrieve the text found in the field "reviews_review" ("Wow, what a great...") when it's found in this particular format with its multiple values? Example:
stdClass Object
(
[node_reviews_nid] => 5270
[reviews_review] => a:2:{s:5:"value";s:38:"Wow, what a great place. The bestest!";s:6:"format";s:13:"filtered_html";}
Those extra values and curly brackets have got me stumped. If I wanted the node_reviews_nid I could simply use $result->node_reviews_nid" - but doing that to get reviews_review just retrieves too much ie,
a:2:{s:5:"value";s:38:"Wow, what a great place. The bestest!";s:6:"format";s:13:"filtered_html";})

The odd curly brackets you're seeing are the result of PHP's serialize function.
Basically it's intended to convert complex structures like objects, nested arrays and so on into simple strings which are easier and safer to transfer, for example over HTTP. Think of it as JSON representation, but specific to PHP (do not attempt to json_decode() a serialized value).
Also worth noting is that serialize-d string has a maximum length, beyond which it's simply truncated, so avoid using it for very large structures - you'll lose data.
The reverse of that is unserialize. So to read the review's text, you would first have to unserialize the "reviews_review" property, then reference the "value" index of the resulting array.
$review_data = unserialize($result->reviews_review);
$review_text = $review_data['value'];
print($review_text);

The data in reviews_review looks like a serialized array i.e. written using the serialize() function
So you will need to unserialize it using unserialize() before you can use it
$review = unserialize($obj->reviews_review);
print_r($review);

Related

Best way to json encode an array that has a json encoded value already? PHP

I have an array with multiple items in it one of which is an already encoded json string. I'm wanting to json encode the whole array but in doing so it re-json_encodes the json and adds slashes to it. The only way I've found to fix this is to json_decode the value and then encode the whole array. I feel like this is a waste of resources though and I feel like there has to be a better way. Is doing it that way the best possible way?
Here's a sample of the array I'm trying to json_encode.
$arr = array();
$arr["var1"] = '{"test":"test"}';
$arr["var2"] = 'foo';
$arr["var3"] = 'bar';
If I don't decode the var1 first and I just encode the whole array I get a result like so
{"var1":"{\"test\":\"test\"}","var2":"foo","var3":"bar"}
Notice the slashes in the json object.
json_encode() returns a string containing the json representation of a value.
In the example, a php string is passed as one element of the array '{"test":"test"}', thus json_encode() is encoding it appropriately into json format, with escaped quotes "{\"test\":\"test\"}".
If decoding nested json is a very resource heavy task, a workaround is to use a placeholder instead of the value, {"var1":"PLACEHOLDER","var2":"foo","var3":"bar"}, and then using str_replace() to replace it.
However, simply decoding it as you described is probably a cleaner solution, if its not resource heavy.

Is there a PHP function to encode/decode a multidimensional array in a string?

Is there a PHP function to encode a generic multidimensional array as a string and get it back as a multidimensional array?
I need it to store in mysql some data (a drupal computed field to be precise). The array contains just floats and strings.
serialize() and unserialize() do what you describe.
http://www.php.net/manual/en/function.serialize.php
http://www.php.net/manual/en/function.unserialize.php
You could also consider encoding the array as JSON with json_encode() and json_decode(), which gives more readable output, if that is important to you.
I second the use of "json_encode" and "json_decode". I believe the output of "json_encode" is less verbose than PHP's serialize function (since data types are inferred) and is immediately more portable (even though that is not a requirement).
Make sure you pass "TRUE" for the second parameter of "json_decode", otherwise you may get a simple object back, depending on how the original data was encoded.

Accessing PHP objects using both naming with reserved characters (-,#) and indexes (0)

In PHP figured out how to use {name-with-reserved-chars} notation to access object data after JSON decode but I also have index values as well in the path (like [0]). My attempts to add the index value has returned nothing despite all my attempts to vary the pattern. Here is an example based on a big JSON object:
["ops:world-patent-data"]["exchange-documents"]["exchange-document"]
[0]["bibliographic-data"]["publication-reference"]["document-id"][0].date.$
my attempt gets nothing:
print $result->{'ops:world-patent-data'}->{'exchange-documents'}->{'exchange-document'}->
{0}->{'bibliographic-data'}->{'publication-reference'}->{'document-id'}->{0}->date;
wondering how to place the 0 and 1 indexes in the path ...
When deserializing an actual JSON list (i.e, not an object but an actual array with numerical indices; something like [1,2,3,...] or also [{...},{...},...]), PHP's parse_json function builds a corresponding PHP array with numerical indices (while on the other hands, it maps JSON objects to instances of the stdClass class -- unless you use the $assoc parameter of the parse_json function).
So, because you are accessing arrays instead of objects, your code would probably have to look like this:
print $result->{'ops:world-patent-data'}->{'exchange-documents'}->
{'exchange-document'}[0]->{'bibliographic-data'}->{'publication-reference'}->
{'document-id'}[0]->date;
It would probably easier to use the $assoc parameter, forcing json_decode to map the entire JSON object with associative arrays, allowing you to use the square bracket notation for object access also.

Problem with json_encode()

i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.

Is json_decode in PHP guaranteed to preserve ordering of elements when returning an array?

You can pass a boolean to json_decode to return an array instead of an object
json_decode('{"foo", "bar", "baz"}', true); // array(0 => 'foo', 1 => 'bar', 2 => 'baz')
My question is this. When parsing object literals, does this guarantee that the ordering of the items will be preserved? I know JSON object properties aren't ordered, but PHP arrays are. I can't find anywhere in the PHP manual where this is addressed explicitly. It probably pays to err on the side of caution, but I would like to avoid including some kind of "index" sub-property if possible.
Wouldn't it make more sense in this case to use an array when you pass the JSON to PHP. If you don't have any object keys in the JSON (which become associative array keys in PHP), just send it as an array. That way you will be guaranteed they will be in the same order in PHP as in javascript.
json_decode('{["foo", "bar", "baz"]}');
json_decode('["foo", "bar", "baz"]'); //I think this would work
If you need associative arrays (which is why you are passing the second argument as true), you will have to come up with some way to maintain their order when passing. You will pry have to do some post-processing on the resulting array after you decode it to format it how you want it.
$json = '{[ {"key" : "val"}, {"key" : "val"} ]}';
json_decode($json, true);
Personally, I've never trusted any system to return an exact order unless that order is specifically defined. If you really need an order, then use a dictionary aka 2dimension array and assigned a place value (0,1,2,3...) to each value in the list.
If you apply this rule to everything, you'll never have to worry about the delivery/storage of that array, be it XML, JSON or a database.
Remember, just because something happens to work a certain way, doesn't mean it does so intentionally. It's akin to thinking rows in a database have an order, when in fact they don't unless you use an ORDER BY clause. It's unsafe to think ID 1 always comes before ID 2 in a SELECT.
I've used json_decode() some times, and the results order was kept intact with PHP client apps. But with Python for instance it does not preserve the order.
One way to be reassured is to test it over with multiple examples.
Lacking an explicit statement I'd say, by definition, no explicit order will be preserved.
My primary line of thought it what order, exactly, would this be preserving? The json_decode function takes a string representation of a javascript object literal as it's argument, and then returns either an object or an array. The function's input (object literal as string) has no explicit ordering, which means there's no clear order for the json_decode function to maintain.

Categories