1

I have a json file which looks like this:

{
"name": "Star_Wars",
"Level": true,
"condition": "HOT",
"actions": [
    {
        "index": 0,
        "name": "Sword_hit",
        "expectedModelName": "SwordModel",
        "params": [
            {
                "name": "LANGUAGE",
                "values": [
                    {
                        "value": "GB"
                    }
                ]
            },
            {
                "name": "PLANET_VERSION",
                "values": [
                    {
                        "value": "HUTTA"
                    }
                ]
            }
        ],
        "newParameters": [],
        "checks": []
    },
    {
        "index": 1,
        "name": "Sword_bash",
        "expectedModelName": "SwordModel2",
        "params": [
            {
                "name": "LANGUAGE",
                "values": [
                    {
                        "value": "IT"
                    }
                ]
            },
            {
                "name": "PLANET_VERSION",
                "values": [
                    {
                        "value": "SCHNUTTA"
                    }
                ]
            }
        ],
        "newParameters": [],
        "checks": []
    }
]

I am trying to parse it with PHP and build URLs out of it. Each "action" is a URL and the parameters are within the "params" section. So the two URLs should be:

index0: LANGUAGE=GB&PLANET_VERSION=HUTTA

index1: LANGUAGE=IT&PLANET_VERSION=SCHNUTTA

My code looks like this so far:

<?php
$json = file_get_contents("data.json");
$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

echo"http://www.myurl.de/test.php?";
foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key=$val&";
    }
}
?>

It works as designed but not as desired ;-) I only need the "params" to build the url. But how can I implement a condition, which only targets the "name" and the "values" from "params" ?

1 Answer 1

1

Please check this simplistic solution:

$data = json_decode($json);
$urls = array();
foreach($data->actions as $k1=>$v1) {
    $urls[$k1] = '';
    foreach($v1->params as $k2=>$v2) {
        $urls[$k1].= $v2->name.'='.$v2->values[0]->value.'&';
    }
    $urls[$k1] = rtrim($urls[$k1],'&');
}
print_r($urls);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this simple but very efficient answer !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.