'where' 喜欢查询数组或对象

'where' like querying an array or object

[{"id":1,"username":"example","email":"example@gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex@ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]

我得到了一个像上面这样的对象。我想要的是 select 例如,id 为 1 的对象。喜欢

select * from object where id=1

和SQL

怎么做?

解码您的对象 (http://php.net/manual/it/function.json-decode.php),然后使用 foreach 遍历您的数组,使用 if 语句检查其中的 id 值。

$obj_to_array = json_decode($json_object);
$target = '';
foreach($obj_to_array as $row){
  if($row['id'] == 1)
    $target = $row;
}

// $target holds your row with id = 1
$data = '[{"id":1,"username":"example","email":"example@gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex@ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';

$data = json_decode($data);

$id = 1;
$key = 'id';
$data = array_filter(
    $data,
    function($value) use ($key, $id) {
        return ($value->$key == $id);
    }
);
var_dump($data);

使用json_decode解码对象。使用下面的代码

    <?php
    $json='[{"id":1,"username":"example","email":"example@gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
    {"id":2,"username":"ex2","email":"ex@ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
    $p = json_decode($json,true);
    $l=count($p);
    for($i=0;$i<=$l;$i++){
    $id=$p[$i]["id"];
if($id==1){
    print_r($p[$i]); // WIll print the id if 1
}
    }

希望对您有所帮助

希望我答对了你的问题。 尝试以下

<?php
$array = json_decode('[{"id":1,"username":"example","email":"example@gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex@ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]');

foreach( $array as $v ) {
  if( $v["id"] == 1 ) {
    echo "I am ID 1";
    break;
  }
}