2016-12-01 99 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';