2016-12-01 136 views

回答

0

你有一個json格式的數組,你需要首先使用json_decode進行解碼。之後循環數組來檢查你想要的id。

因此,代碼應該是這樣的:

$json = '[{"ID":1},{"ID":2}]'; 
$id = 1; 

$data = json_decode($json, true); 
foreach($data as $item){ 
    if($item['id'] == $id) { 
     echo 'it exists'; 
    } 
} 
+0

json_decode90期望參數1是字符串,數組給定 –

0

迭代數組使用for循環,並使用值作爲參數去json_decode

$id = 1; 
$arr = array('{"ID":1}', '{"ID":2}'); 
foreach($arr as $val) { 
    if (in_array($id, json_decode($val, TRUE))) { 
    echo "id present"; 
    } 
} 
2

您可以嘗試Laravel的Collection::contains方法,例如:

$collection = collect(json_decode($jsonString, true)); 

if ($collection->contains(1) { 
    // Exists... 
} 

此外,您還可以使用鍵/值對這樣的:

if ($collection->contains('ID', 1) { 
    //... 
} 

另外,如果你想獲得該項目從集合然後你可以嘗試where是這樣的:

$id = $collection->where('ID', 1)->first(); // ['ID' => 1] 
0

試試這個,如果值是存在的,它會給陣列

的關鍵
$jsondata = '[{"ID":1},{"ID":2}]'; 
$array = json_decode($jsondata,true); 

$key = array_search(1, array_column($array, 'ID')); 
0

只是檢查如果字符串是JSON數組中,很少計算。

我認爲這是更有效的方法。檢查結果here

<?php 
$id = 1; 
$array = ['{"ID":1}', '{"ID":2}']; 
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';