Paolo Pedrazzi Paolo Pedrazzi - 10 months ago 36
JSON Question

Extract value from a multidimensional array

I have this string:

O:37:"Ivory\GoogleMap\Service\Base\Distance":2:{s:43:"Ivory\GoogleMap\Service\Base\Distancetext";s:6:"572 km";s:44:"Ivory\GoogleMap\Service\Base\Distancevalue";i:572343;}

need to return only 572343 value.


This is not an array but a Google object that has been serialised. It expects you to have an object called Distance in the Ivory\GoogleMap\Service\Base\ namespace.

I found a github repo that seems to handle that.

If that's not what you want you could try something a bit inelegant like reading backwards from the end of the string until you have all the digits.

$output = '';
for ($i = -1; is_numeric(substr($string, $i,1)); $i--) {
    $output = substr($string, $i,1).$output;
echo $output;

or you could try explode using '";i:' as the token and grab the second element.

$pieces = explode('";i:', $string);
$number = str_replace(';}','',$pieces[1]);
echo $number;

Or you could do something a bit more stable with a regex (which as you might guess, I do not enjoy).

Update: from OP comments it seems that they are actually struggling with using a set of Google Ivory objects and not a string at all. That's a whole other question. However, if that were the string they needed to parse, my answer would help.