用php检索JSON的元素

时间:2017-12-26 04:08:53

标签: php json

我从原始格式的网站获得了一个JSON:

{
    "A_B" : {
        "id" : 7,
        "last" : "0.00000038"
    },
    "A_C" : {
        "id" : 8,
        "last" : "0.00001938"
    },
    ...
}

由此我获得了一个包含所有$c

的唯一数组"A_B", ...

我无法找到正确的语法来获取密钥'id', 'last'c[0]的值。

3 个答案:

答案 0 :(得分:2)

一个基本的PHP示例:

$raw = '{
        "A_B" : {
            "id" : 7,
            "last" : "0.00000038"
        },
        "A_C" : {
            "id" : 8,
            "last" : "0.00001938"
        }
    }';

// Translate from JSON to data object
$data = json_decode($raw);

// Read variables from the data object
echo 'Option 1)<br />
data->A_B->id = '.$data->A_B->id.'<br />
data->A_B->last = '.$data->A_B->last.'<br />';

// Extract and read a single object 
$c = $data->A_B;
echo 'Option 2)<br />
c->id = '.$c->id.'<br />
c->last = '.$c->last.'<br />';

// To an array version. Note: 'true' is included
$ar = json_decode($raw, true);

// Reading a array 
echo 'Option 3)<br />
ar[A_B][id] = '.$ar['A_B']['id'].'<br />
ar[A_B][last] = '.$ar['A_B']['last'].'<br />';

// And finally, I think what you have done
$c = $ar['A_B'];

echo 'Option 4)<br />
c[id] = '.$c['id'].'<br />
c[last] = '.$c['last'].'<br />';

将呈现以下内容:

Option 1)
data->A_B->id = 7
data->A_B->last = 0.00000038
Option 2)
c->id = 7
c->last = 0.00000038
Option 3)
ar[A_B][id] = 7
ar[A_B][last] = 0.00000038
Option 4)
c[id] = 7
c[last] = 0.00000038

修改即可。我想我明白你的意思。请参阅以下更新的PHP脚本。

$raw = '{
    "A_B" : {
        "id" : 7,
        "last" : "0.00000038"
    },
    "A_C" : {
        "id" : 8,
        "last" : "0.00001938"
    }
}';

// Only interested in these valves from the JSON
// Value 'X_Y`' is expected to fail!
$knownId = array('A_C','X_Y');

// Extract JSON to array
$c = json_decode($raw,true);

// Only print values that match $knownId
foreach($knownId as $k => $v) {
    if ($c[$v]) {
        echo '<p>v:['.$v.'] 
             id:['.$c[$v]['id'].'] 
             last:['.$c[$v]['last'].']</p>';
    }
}

哪个会显示$raw中的示例数据的单个结果。

v:[A_C] id:[8] last:[0.00001938]

答案 1 :(得分:0)

尝试这个假设您通过json_decode获取数组($ jsnstr,true)

 $id = $c[0]["id"];
 $last = $c[0]["last"];

你也可以在for循环中使用它,并使用循环索引i作为数组索引

答案 2 :(得分:0)

嗨使用以下内容,您可以获得&#34; id&#34;和&#34;最后&#34;

$json_raw = '{
    "A_B" : {
        "id" : 7,
        "last" : "0.00000038"
    },
    "A_C" : {
        "id" : 8,
        "last" : "0.00001938"
    }
}';

//decode the json 
$data = json_decode($json_raw);


$c = array();

foreach ($data as $key => $value) {
    //collect the keys
    $c[] = $key;
}

$c = array_unique($c);

foreach ($data as $key => $value) {

    //check the key is exist
    if(in_array($key, $c)){

        // do computation
        $id = $value->id;
        $last = $value->last;

        echo "Key is :".$key."  , id :".$id." , last :".$last."\n";
    }


}

输出

Key is :A_B  , id :7 , last :0.00000038
Key is :A_C  , id :8 , last :0.00001938