Prince Prince - 11 months ago 34
PHP Question

How to decode a json string with selecting the first one

I have some string like this

$string = {"71":"message1","72":"message2" }

The 71 and 72 are the id

I want to select ids from $string and pass them to some function like this:

$id = array('71','72')
$collection = Mage::getModel('model/model')->load($id);

How can I parse the string and get the id of each one of them.

Answer Source

That is a json string, so it's fairly easy to get the data out.

$string = '{"71":"message1","72":"message2" }';
$array = json_decode($string, TRUE); // put it into an associated array
$keys = array_keys($array); // get the keys

Or as a one-liner:

$keys = array_keys(json_decode($string, TRUE));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download