Mayank pandey
Mayank pandey

Reputation: 81

How to parse separate json arrays inside existing json in php?

Let me describe in detail, I have a json as below :

{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}

What I want is separate rawdata in json only . There can be n numbers of rawdata data . I need to iterate & segregate based on task id .

I am stuck cannot proceed till now what I wrote :

<?php

require_once 'execute_query.php';    
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $rawdata = file_get_contents("php://input");
    $array=json_decode($rawdata, true);    
}    
var_dump ($array);    
$clientId= $array[client_id];    
echo $clientId;
//print_r(array_keys($array));
?>

So to brief :

Input is :

{
    "client_id": 1234,
    "rawdata": [{
        "task_id1": {
            "apikey1": "1234",
            "flow": "ssp",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        },
        "task_id2": {
            "apikey2": "1235",
            "flow": "mobileweb",
            "total_chocolate_request": 43235,
            "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
            "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
        }
    }]

}

Output : There are two taskids & there respective json are

{
"task_id1": {
    "apikey1": "1234",
    "flow": "ssp",
    "total_chocolate_request": 43235,
    "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
    "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
}

and

{

"task_id2": {
                "apikey2": "1235",
                "flow": "mobileweb",
                "total_chocolate_request": 43235,
                "start_time": "2017 - 05 - 09 12: 29: 00 UTC",
                "end_time": "2017 - 05 - 09 12: 29: 00 UTC"
            }

Upvotes: 1

Views: 37

Answers (1)

delboy1978uk
delboy1978uk

Reputation: 12365

This is real easy. JSON decode into an array. Grab what you need. You can json_encode() back if you need to.

$array = json_decode($json, true);

$rawDatas = $array['rawdata'][0];

foreach($rawDatas as $key =>$data) {
    echo $key."\n......\n";
    var_dump($data);
    echo "............\n";
}

See it in action here: https://3v4l.org/bF9mt

Upvotes: 1

Related Questions