Ben H Ben H - 3 months ago 25x
PHP Question

get last value from JSON array

I have a JSON string within a MySQL database which I could like to get 2 numbers from within WordPress.

My string is as follows:


is the course ID. Within the
is both
. These are the IDs of each page completed. I need to get the last one of these which in this case would be

I basically need something that would do the following:

Get Page ID
Find Page ID in JSON string
Get the last ID from JSON string topics

How would I go about this?


What you posted is not a JSON, it's a result of PHP serialization that is done through serialize() function.

In order to use the values, you have to get this string and pass to the unserialize() function, which will give you... well, it will give you an error:

PHP Notice: unserialize(): Error at offset 5 of 235 bytes

That's because you assumed it was JSON and formatted it for us. It's okay for JSON and death to serialized string. You need to get rid of whitespaces:


After you do unserialize() on it, you will get:

    [300] => Array
            [lessons] => Array
                    [302] => 1

            [topics] => Array
                    [302] => Array
                            [304] => 1
                            [311] => 1


            [completed] => 1
            [total] => 4

So, you get a PHP array in $a and now you can do whatever you want with it:

$courseID = 300;
$lessons = array_keys($a[$courseID]['lessons']);
$topics = array_keys($a[$courseID]['topics']);
$pages = array_keys($a[$courseID]['topics'][ $topics[0] ]);
$lastPage = $pages[ count($pages)-1 ];

You will have 302 in $topics, 304 and 311 in $pages and 311 in $lastPage.

Sidenote: How to distinguish JSON from PHP serialization

This is a bit of a simplification, but it's good for memorization. Whenever I see a bunch of <one-letter>:<number>:<value> periods, I assume that it's the serialization result, where <one-letter> is type (array, string, integer) and <number> is a length in characters or array elements (omitted for integer). If instead of <one-letter> I see descriptive variable names, enclosed in "quotation_marks", or arrays that are wrapped in [square brackets], I assume it's JSON.