PHP检查变量,如果存在于json数组中

时间:2016-12-01 10:48:12

标签: php laravel

Array :  [{"ID":1},{"ID":2}]

$id=1;

我想检查数组中是否存在$id

谢谢!

5 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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';
   }
}

答案 2 :(得分: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";
  }
}

答案 3 :(得分:0)

试试这个,如果值存在,它将给出数组的键

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

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

答案 4 :(得分:0)

只需检查字符串是否在json数组中,几乎没有计算。

我认为这是更有效的方式。检查结果here

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