Jump to content

Problem in array typecast


girish.kc

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.