2

I have a JSON object and selector string like this.

$json = '
{
    "hotels" : { 
        "hotel" : [
            { "ort": "rom", "lioc": "inrom" },
            { "ort": "paris", "lioc": "inpsrisd" },
            { "ort": "berlin", "lioc": "inberlin" },
            { "ort": "milano", "lioc": "inmilano" },
            { "ort": "paris", "lioc": "anotherinpsrisd" },
            { "ort": "muc", "lioc": "inmuc" }
        ]
    }
}
';
$selector = "hotels.hotel.0,hotels.hotel.5";

I'd like to get the following results from $selector

{"hotels":{"hotel":[{"ort":"rom","lioc":"inrom"},{"ort":"muc","lioc":"inmuc"}]}}

If the depth of the selector is fixed then this is pretty simple.

$jsonArr = json_decode($json, TRUE);
$sel_arr = explode(",", $selector);

$list = array();
foreach($sel_arr as $item){
   $node = explode(".", $item);
   if(isset($jsonArr[$node[0]][$node[1]][$node[2]])){
       array_push($list, $jsonArr[$node[0]][$node[1]][$node[2]]);
   }
}
$result['hotels']['hotel'] = $list;

var_dump(json_encode($result));

The point is that don't know JSON object structure and depth of selector. The example mentioned above is only a simple example for understanding.

As a result I have to get the following PHP array.

$result['hotels']['hotel'][] = ["ort"=>"rom","lioc"=>"inrom"];
$result['hotels']['hotel'][] = ["ort"=>"muc","lioc"=>"inmuc"];

So I have to create a multi-level array($result) according to the depth of the selector(in this example depth = 3)

If $selector = "hotels.hotel.bla.bla.0,hotels.hotel.bla.bla.5"; and $json is changed according to the $selector then $result need to following structure.

 $result['hotels']['hotel']['bla']['bla'][] = ["ort"=>"rom","lioc"=>"inrom"];
 $result['hotels']['hotel']['bla']['bla'][] = ["ort"=>"muc","lioc"=>"inmuc"];

selector's depth is dynamic and $json structure is also dynamic.

How can I solve this problem?

Web Star
  • 431
  • 3
  • 20

0 Answers0