[{"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
怎么做?
答案 0 :(得分:0)
解码你的对象(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
答案 1 :(得分:0)
$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);
答案 2 :(得分:0)
使用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
}
}
希望这有助于你
答案 3 :(得分:0)
我希望我的问题是正确的。 请尝试以下
<?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;
}
}