Justme
Justme

Reputation: 221

How to search in Json structure in PHP?

From a API call in get in PHP

$data = file_get_contents('https://api.kraken.com/0/public/Ticker?pair=' . $pair);
$data_array = json_decode($data,true);

I get the following Json string.

{
    "error": [],
    "result": {
        "XXMRZEUR": {
            "a": [
                "188.16000000",
                "1",
                "1.000"
            ],
            "b": [
                "187.75000000",
                "4",
                "4.000"
            ],
            "c": [
                "188.29000000",
                "0.61088847"
            ],
            "v": [
                "1048.17596252",
                "2531.03697810"
            ],
            "p": [
                "188.83522852",
                "192.55432502"
            ],
            "t": [
                636,
                1696
            ],
            "l": [
                "186.50000000",
                "186.50000000"
            ],
            "h": [
                "195.90000000",
                "198.16000000"
            ],
            "o": "195.51000000"
        }
    }
}

I would like to get the first element after the C. Therefore I run.

$data = file_get_contents('https://api.kraken.com/0/public/Ticker?pair='.$pair);
$data_array = json_decode($data,true);
$result = array_search('c', array_column($data_array, 'XXMRZEUR'));

The problem in this is that do not know the XXMRZEUR code so I only want to match with the value c and the get the first value of c.

I tried several things with array_search, a function call array_find_deep, and some other functions which are mentioned on: http://www.php.net/manual/en/function.array-search.php#106904 but I could not get it working well.

I also tried:

$key = $data_array->result;

but this gives me a NULL as well

I also tried

foreach ($data_array['result'] as $item) {
    \kint::dump($item);
}

This gives me a array of 9 element on the result. When I change the code to :

foreach ($data_array['result']['c'] as $item) {
    \kint::dump($item);
}

I get the value of NULL again.

Then I tried a loop

foreach ($data_array['result'] as $item) {
    \kint::dump($item); 
    if ($item == "c"){
        foreach ($item as $itemlevel) {
            \kint::dump($itemlevel);
        }
    }
}

Bu this i not working as well. I'm getting null as a result.

So I tried:

foreach ($data_array['result'] as $item) {
    \kint::dump($item['c'][0]);
    $result = $item['c'][0];    
}

This works. But I still need the string 'result' as a fixed point which I do not want.

How to get the value of 188.29000000 with only the parameter c als a given position with in a very efficient way?

Upvotes: 0

Views: 183

Answers (3)

Robert
Robert

Reputation: 5963

If you look at the kraken api documenation, you'll see this:

error = array of error messages in the format of:
    <char-severity code><string-error category>:<string-error type>[:<string-extra info>]
    severity code can be E for error or W for warning
result = result of API call (may not be present if errors occur)

So it would be safe to assume that if you have no errors, result will always hold the result of the call.


To explain what's working an what not.

I also tried:

$key = $data_array->result;

but this gives me a NULL as well

You use $data_array = json_decode($data,true);, the true flag will convert the json string into an associative array. Using the -> will not work for arrays in PHP.

This is why you get NULL when you use $data_array->result and the contents of the result key when you use $data_array['result'].


foreach ($data_array['result']['c'] as $item) {
    \kint::dump($item);
}

I get the value of NULL again.

This is because you are missing the XXMRZEUR key in between.

If you were to use $data_array['result']['XXMRZEUR']['c'], you would have dumped the items correctly.


To answer your question, I would first check if there are no errors, otherwise result may or may not be there. After that you can just fetch the result, check if the key is present and get the value you want.

$data = file_get_contents('https://api.kraken.com/0/public/Ticker?pair=' . $pair);
$data_array = json_decode($data,true);

if (isset($data_array['error']) && !empty($data_array['error'])) {
    print_r($data_array['error']);
    // ... handle error
    die();
}

// get result
$result = $data_array['result'] ?? [];

// you would want the contents of the first key XXMRZEUR
// current will return the value of the current pointer
$item = current($result);

// check if $item['c'][0] exists and output it, otherwise nope
if (isset($item['c'][0])) {
    print_r($item['c'][0]);
} else {
    print_r('nope');
}

Upvotes: 1

Zafahix
Zafahix

Reputation: 161

You can use simple function to search key "c" in multidimensional array. This code will give the wanted result.

<?php
function searchArray( array $array, $search )
{
    while($array) {
        if(isset($array[$search])){ return $array[$search]; } 
        $segment = array_shift($array);
        if(is_array($segment)){
            if($return = searchArray($segment, $search)){ return $return; }
        }
    }
    return false;
}

$data = '{"error":[],"result":{"XXMRZEUR":{"a":["188.16000000","1","1.000"],"b":["187.75000000","4","4.000"],"c":["188.29000000","0.61088847"],"v":["1048.17596252","2531.03697810"],"p":["188.83522852","192.55432502"],"t":[636,1696],"l":["186.50000000","186.50000000"],"h":["195.90000000","198.16000000"],"o":"195.51000000"}}}';
$data_array = json_decode($data,true);

$result = searchArray($data_array, "c");

print_r($result);
?>

Upvotes: 0

Philipp
Philipp

Reputation: 15629

You could use current, to get the first element of an array.

$data = json_decode($json, true);
$result = $data['result'];
$items = current($result);
print_r($items['c']);

Upvotes: 0

Related Questions