-1

I have some string like this $string = {"71":"message1","72":"message2" } The 71 and 72 are the id's

I want to select these ide's 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.

PЯINCƎ
  • 646
  • 10
  • 28

2 Answers2

3

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));
aynber
  • 22,380
  • 8
  • 50
  • 63
  • it works thanks,however i want to know if i can replace the keys(the ids) with their equivalent for exemple 71 i replace it with : name1 – PЯINCƎ Dec 28 '16 at 17:56
  • It depends on what exactly you're looking for, and where you're getting name1. – aynber Dec 28 '16 at 18:31
  • You'll have to process that in a loop and create a new array with that information. – aynber Dec 28 '16 at 18:44
  • It's been a long time since I've messed with Magento, so I couldn't tell you. I'd suggest opening a new question with that question. – aynber Dec 28 '16 at 18:50
2
<?php
    $string = '{"71":"message1","72":"message2" }';
    $keys = array_keys(json_decode($string, TRUE));
    print_r($keys);

output:

Array ( [0] => 71 [1] => 72 )

json The json string being decoded.

This function only works with UTF-8 encoded strings.

Note: PHP implements a superset of JSON as specified in the original » RFC 7159. assoc When TRUE, returned objects will be converted into associative arrays.

depth User specified recursion depth

Return Values Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Reference: http://php.net/manual/en/function.json-decode.php

Md. Abutaleb
  • 1,590
  • 1
  • 14
  • 24