比方說,我有這個 JSON 資料,我想按名稱“id”列印所有鍵,我該怎么辦?
$json = {"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}
我試過這個,但這個只給了我第一個陣列物件子鍵(即 id=37)我想要的都喜歡(id=37,id=38)
$op = $json->{'response'}[0]->{'id'};
uj5u.com熱心網友回復:
您可以遍歷您的回復
$array = [];
foreach ($json->{'response'} as $reponseItem){
$array[$reponseItem['id']] = $reponseItem;
}
uj5u.com熱心網友回復:
如果我假設你的 JSON 真的是 JSON,因此是一個字串,你可以這樣做:
$json = '{"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$data = json_decode($json);
$ids = array_column($data->response, 'id');
print_r($ids);
這將導致:
Array
(
[0] => 37
[1] => 38
)
請參閱PHP Fiddle。
您可以使用json_decode()將 JSON 字串轉換為可用的 PHP 資料。
獲取 id 的方法是使用array_column()。
uj5u.com熱心網友回復:
您需要將 json 字串解碼為第一個陣列,然后回圈遍歷資料。
$json = ' {"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$jsonArray =json_decode($json,true); //convert your json string to array.
$newJson = $jsonArray ['response'];
foreach($newJson as $data)
{
echo $data['id'];
}
或者您可以直接回圈通過您的$jsonArray['response'].
foreach($jsonArray['response'] as $data)
{
echo $data['id'];
}
uj5u.com熱心網友回復:
$json = '{"response":[
{
"id": 37,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "38"
},
{
"id": 38,
"slug": "red",
"stock": true,
"name": "Red",
"default": 0,
"sizes": "40"
}
]}';
$data = json_decode($json); // we decode the JSON
$num = count($data->response); // we count how many response keys we have
$i=0; // define $1=0 to start our iteration
while ($i < $num) { // $i must be < than the counted array keys
$op = $data->response[$i]->id; // we tell the while loop to iterate over the array
print $op."</br>"; // prints out 37 & 38
$i ; // Standard incrementation
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439550.html
