我有一个存储在数据库中的json,看起来像这样
TreeSet
我正在检索它
[{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"gorilla-preview"}]
它的输出看起来像这样
while($row = mysqli_fetch_assoc($res)){
$array[] = json_decode($row['element']);
}
echo "<pre>";
print_r($array);
我的问题是:如何以正确的格式获取所有这些值?
答案 0 :(得分:1)
您可能必须再次循环,因为您将已解码的JSON数据存储在数组中。因此,要获取存储在JSON对象中的唯一值,您需要第二个循环,如下所示:
注意:从JSON数据的结构来看,很明显你需要一个嵌套的循环...
<?php
foreach($array as $index=>$arrData){
foreach($arrData as $key=>$objData){
// DO SOMETHING WITH THE INTERNAL VALUES OF THE JSON DATA.
var_dump($objData->class);
var_dump($objData->name);
var_dump($objData->value);
var_dump($objData->id);
}
}
或者,您可以(如果您愿意)跳过将数据存储在数组中并直接在第一个循环中使用它,如下所示:
<?php
while($row = mysqli_fetch_assoc($res)){
$objData = json_decode($row['element'][0]);
// DO SOMETHING WITH THE DATA LIKE BUILD A DYNAMICALLY GENERATED HTML STRING.
echo "<p class='{$objData->class}' id='{$objData->id}'>{$objData->value}</p>;
}
<强>更新强>
根据您的评论,如果您有一个JSON数据,例如:[{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"gorilla-preview"}]
下面的代码段(您可以Quick-Test Here)显示您可以如何访问您的数据:
$json = '[{"class":"button-input btn btn-warning","name":"gorilla-preview","value":"Goat","id":"gorilla-preview"}]';
$arrData = json_decode($json);
foreach($arrData as $key=>$objData){
// DO SOMETHING WITH THE INTERNAL VALUES OF THE JSON DATA.
var_dump($objData->class); //<==YIELDS:: string 'button-input btn btn-warning' (length=28)
var_dump($objData->name); //<==YIELDS:: string 'gorilla-preview' (length=15)
var_dump($objData->value); //<==YIELDS:: string 'Goat' (length=4)
var_dump($objData->id); //<==YIELDS:: string 'gorilla-preview' (length=21)
}
答案 1 :(得分:1)