duanjiangzhi6851
2018-05-07 08:21
浏览 99
已采纳

如何在PHP中搜索Json结构?

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题