我有一个数组,当我尝试打印_r时,它是这样的:
Array ( [user_id] => Erick ) Array ( [user_id] => Baldi) Array([user_id]=> Bintang ) Array ( [user_id] => Bagas ) Array ( [user_id] => Baim )
我的预期输出就像:
Array (
Array (
[user_id] => Erick
)
Array (
[user_id] => Baldi
)
Array (
[user_id] => Bintang
)
Array (
[user_id] => Bagas
)
Array (
[user_id] => Baim
)
)
这里有人有主意吗?我受够了。这是我的php代码:
public function get_userid() {
// $action = $this->input->post('action');
$customerField = $this->input->post('customer');
$projectField = $this->input->post('project');
$user_roleField = $this->input->post('role');
for ($i=0; $i<count($customerField); $i++) {
for ($j=0; $j<count($projectField); $j++) {
for ($k=0; $k<count($user_roleField); $k++) {
array_push($test, $this->get_array_push($customerField[$i], $projectField[$j], $user_roleField[$k]));
}
}
}
}
public function get_array_push($customer, $project, $user_role) {
$query = $this->db->query("SELECT user_id
FROM `ixt_user_project_list`
LEFT JOIN ixt_user_type ON ixt_user_project_list.user_type = ixt_user_type.user_type
WHERE ixt_user_project_list.user_cust_id ='".$customer."'
AND ixt_user_project_list.user_project_id ='".$project."'
AND ixt_user_type.user_owner ='".$user_role."'")->result_array();
//Filter null array
foreach ($query as $key => $value) {
print_r($value);
}
}
这是我的初始查询值:
Array ( [0] => Array ( [user_id] => Erick ) ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( ) Array ( [0] => Array ( [user_id] => Baldi ) [1] => Array ( [user_id] => Bintang ) ) Array ( [0] => Array ( [user_id] => Bagas ) [1] => Array ( [user_id] => Baim ) )
正如@scaisEdge所写的那样——这是因为您在foreach
循环中使用了print_r
。
如果你想过滤null
结果,你可以使用数组过滤器作为:
$arr = array(array("user_id" => "aaa"), null, array(), array("user_id" => null), array("otherField" => "bbb"));
$filterdResult = array_filter($arr, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"]));
});
现在你只需要做print_r($filterdResult );
这将输出:
Array
(
[0] => Array
(
[user_id] => aaa
)
)
编辑:将新输入设置为:后
$query = array(array(array("user_id" => "aaa"), null, array(), array("user_id" => null)), array(array("user_id" => "ccc"), null, array(),array("user_id" =>"ddd")));
您可以使用以下内容:
$res = array();
//Filter null array
foreach ($query as $key => $value) {
array_push($res, array_filter($value, function($elem) {
return ($elem && array_key_exists("user_id", $elem) && !is_null($elem["user_id"])); }));
}
print_r($res);
哪个输出:
Array
(
[0] => Array
(
[0] => Array
(
[user_id] => aaa
)
)
[1] => Array
(
[0] => Array
(
[user_id] => ccc
)
[3] => Array
(
[user_id] => ddd
)
)
)
如果需要,可以从这里进行压平。
@David Winder我试图将空数组过滤器作为您的建议进行组合。
$res = array();
//Filter null array
foreach ($query as $key => $value) {
if (!is_null($value)) {
$res[] = $value;
//print_r($res);
}
}
但是,当我在foreach循环中打印_r($res(时,结果变成了所有数组值中的重复数组。