簡體   English   中英

PHP JSON獲取每個鍵的特定值

[英]PHP JSON getting specific value of each key

我有一個讀取JSON文件的php代碼。 以下JSON示例的一部分:

 "Main": [{
    "count": 7,
    "coordinates": [89,77],
    "description": "Office",
  },{
    "count": 8,
    "coordinates": [123,111],
    "description": "Warehouse",
  }]

而且我正在嘗試對PHP進行編碼,以僅獲取那些描述的信息(計數,坐標,描述),這些信息包括在Warehouse之類的條件中。 下面的PHP示例

$validcriteria = array("Warehouse", "Parking_lot");

我如何執行if語句來首先檢查有效條件中是否包含“描述”。 我嘗試了下面的代碼,但似乎無法正常工作。

$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
    if (in_array($key['description'] , $validcriteria))
    {
        #more codes here
    }
}

我的PHP代碼一直在工作,除了當我嘗試添加$key['description']嘗試首先檢查描述是否有效時。 上面的代碼經過了重構,可以刪除敏感信息,但是希望您對我正在嘗試執行的操作有所了解。

嘗試了解已解析的JSON字符串的結構時,請從print_r($JSONFile); 檢查其內容。 在您的情況下,您會發現有一個外鍵'Main' ,其中包含一個子數組數組。 您將需要遍歷該外部數組。

// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
  // The sub-array $value is where to look for the 'description' key
  if (in_array($value['description'], $validcriteria))
  {
    // Do what you need to with it...
  }
}

注意:如果您希望繼續在json_decode()中將$assoc參數設置為false ,請檢查結構以了解對象的布局,並使用->運算符而不是數組鍵。

$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
  // The sub-array $value is where to look for the 'description' key
  if (in_array($value->description, $validcriteria))
  {
    // Do what you need to with it...
  }
}

您可能還考慮使用array_filter()進行測試:

$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
  return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria

給定您的JSON結構,您可能想要

foreach($decoded_json['Main'] as $sub_array) {
    if (in_array($sub_array['description'], $validation)) {
       ... it's there ...
    }
}

因為您將json_decode函數的第二個參數設置為false,所以它將作為對象返回,如果將其更改為TRUE,則該代碼將起作用。

http://php.net/manual/en/function.json-decode.php

而且您必須將價值的關鍵改變;

foreach ($JSONFile->Main as $key => $value)
{
    if (in_array($value->description, $validcriteria))
    {
        #more codes here

    }
}

此代碼假定您的json文件比您的示例具有更大的深度。 這就是為什么foreach循環中$ JSONFile-> Main的原因。

嘗試使用:

if ( array_key_exists('description', $key) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM