Jump to content

Recommended Posts

I am using the json_encode function  to store the data in the following format.

 

{"0":"1.1","900":"1.2","1800":"1.3","2700":"1.4","3600":"2.1","4500":"2.2","5400":"2.3","6300":"2.4","7200":"3","8100":"3"}

 

After retrieval, I am decoding the encoded json string and typecasting it to an array as bellow: 

$data = array();
$data = (array)json_decode($db_data);

echo array_search(1.2,$data); 

echo 'Value : '. $data[900];



 

The first echo statement returns 900 as the key, but the second echo returns blank. The array has all the values, is_array($data) returns true.

 

If I add the bellow code then the things work normally.

 

$test_array = array();
foreach ($data as $key => $value
{
        $test_array[$key] = $value;
}

echo array_search(1.2,$test_array); 

echo 'Value : '. $test_array[900];

 

Looks strange to me.

Please advice.

 

Link to comment
https://forums.phpfreaks.com/topic/214895-problem-in-array-typecast/
Share on other sites

json_decode returns an object by default. You need to set the second parameter 'true' to return an array:

 

$data = json_decode($db_data, true);

 

The problem with your method of typecasting the object will have been within the conversion, but I'm not sure what exactly.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.