我想从一个[]调用所有名称,数组不能使用foreach php吗?或者我不能做我想做的事情,我使用了foreach(“id”,“NOT LIKE”,$ id),但是当使用foreach的echo形式时,只显示一个名字, 这是我的PHP代码:
if ($getusers !== FALSE) {
$json["error_two"] = FALSE;
foreach($db->get("users",array('id', 'NOT LIKE', $id))->results() as $u){
$user = new user( $u->id );
$json = array(
'error_two' => FALSE,
'getusers' => $getusers,
'call_two' => [
array(
'user_id' => $user->data()->id,
'fname' => $user->data()->fname,
'lname' => $user->data()->lname,
'username' => $user->data()->username,
'gender' => $user->data()->gender,
),
]
);
echo json_encode($json);
}
}
出:
{"error_two":false,"getusers":true,"call_two":[{"user_id":"1","fname":"Ned","lname":"Stark","username":"","gender":"Male"}]}{"error_two":false,"getusers":true,"call_two":[{"user_id":"3","fname":"Danyal","lname":"Join","username":"","gender":"Male"}]}{"error_two":false,"getusers":true,"call_two":[{"user_id":"4","fname":"dnianas","lname":".co","username":"","gender":"Male"}]}{"error_two":false,"getusers":true,"call_two":[{"user_id":"5","fname":"Mr.","lname":"Robot","username":"","gender":"Male"}]}
我想要的是:
{
"call_two" : [
{
"user_id" = "1",
"fname" = "Ned",
"lname" = "Stark",
"username" = "",
"gender" = "Male"
},
{
"user_id" = "2",
"fname" = "Jon",
"lname" = "Snow",
"username" = "",
"gender" = "Male"
},
{
"user_id" = "3",
"fname" = "Danyal",
"lname" = "Join",
"username" = "",
"gender" = "Male"
}
]
}
答案 0 :(得分:0)
...我使用了foreach(“id”,“NOT LIKE”,$ id),但是当使用foreach中的echo形式时,只显示一个名字......
那是因为你在$json
循环的每次迭代中都覆盖了foreach
。此外,这不是您提到的那里的无效JSON字符串。要实现有效(并且有点预期的JSON字符串),您的if
块应该是这样的:
if ($getusers !== false) {
$json = array('error_two' => false, 'getusers' => $getusers);
foreach($db->get("users",array('id', 'NOT LIKE', $id))->results() as $u){
$user = new user( $u->id );
$json['call_two'][] = array(
'user_id' => $user->data()->id,
'fname' => $user->data()->fname,
'lname' => $user->data()->lname,
'username' => $user->data()->username,
'gender' => $user->data()->gender,
);
}
echo json_encode($json);
}
答案 1 :(得分:0)
您正在覆盖'call_two'
而不是向该数组添加出现
if ($getusers !== FALSE) {
$json = array();
$json["error_two"] = FALSE;
$json['getusers'] = $getusers;
foreach($db->get("users",array('id', 'NOT LIKE', $id))->results() as $u){
$user = new user( $u->id );
$call_two[] = array(
'user_id' => $user->data()->id,
'fname' => $user->data()->fname,
'lname' => $user->data()->lname,
'username' => $user->data()->username,
'gender' => $user->data()->gender,
);
);
}
$json['call_two'] = $call_two;
}
echo json_encode($json);