[{"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"}]
我得到了一个像上面这样的对象。例如,我想要的是选择 id 为 1 的对象。喜欢
select * from object where id=1
与 SQL 一起使用
怎么办?
我希望我答对了你的问题。尝试以下操作
<?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;
}
}
解码你的对象 (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
}
}
希望这对你有帮助