【发布时间】:2015-10-21 22:10:36
【问题描述】:
这是一个奇怪的问题。执行查询时,如果找到值 0(int 类型),它将返回 null。
这是我的mysql函数:
public function query( $query_string, $params = null, $param_types = null) {
//prepare the statement
$stmt = $this->db->prepare($query_string);
//check if the sql query is wrong.
if($stmt === false) {
echo "Wrong SQL: " . $query_string;
if(DEBUG)
echo "<br />Error: " . $this->db->errno . " " . $this->db->error;
return;
}
if($params != null && $param_types != null) {
//build the array that needs to pass the args to bind_param.
$a_params = array();
$a_params[] = &$param_types;
for($i=0; $i<count($params); $i++)
$a_params[] = &$params[$i];
// $stmt->bind_param('s', $param); equivalent
call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
//run the query
$stmt->execute();
//bind the result
$data = $stmt->result_metadata();
$fields = $out = $results = array();
$count = 0;
$k = 0;
if( $data != null ) {
while($field = $data->fetch_field())
$fields[$count++] = &$out[$field->name];
call_user_func_array(array($stmt, 'bind_result'), $fields);
// fetch the result
while ($stmt->fetch())
$results[$k++] = array_flip(array_flip($out));
}
$stmt->close();
return $results;
}
}
MySQL 查询:
public function getMenuItems( $id ) {
$items = $this->db->query("SELECT id, menu, parent_id, name, url, external, position FROM menu_meta WHERE menu = ? ORDER BY position ASC", array($id), "i");
return $items;
}
我的数据库在表中有以下项目: https://gyazo.com/d9a0a9472b0b51d43aafeafdd28a75c8
如您所见,我需要显示 0 的值。它们不为空!
使用 json_encode 这是输出:
[{"menu":1,"position":0,"name":"Home","url":"..\/"},{"id":5,"menu":1,"parent_id":2,"name":"Add New","url":"#","position":0},{"id":2,"position":1,"external":0,"name":"Customers","url":"..\/?page=customers"},{"id":3,"menu":1,"external":0,"name":"Subscriptions","url":"..\/?page=subscriptions","position":2},{"id":4,"menu":1,"external":0,"name":"Billing","url":"..\/?page=billing","position":3}]
这是服务器的配置问题吗?或者也许是我的 PHP 版本?
编辑:没有“null”的值,而是键+值完全丢失。 JSON 中的第一个条目缺少键“id”,因为值为 0。其他条目缺少“parent_id”,因为值为 0。
【问题讨论】:
-
我在 JSON 中没有看到任何
null。 -
@Barmar 好吧,没有 null 的值,而是根本没有值..(或关键)
-
array_flip(array_flip($out))是干什么用的?为什么要翻转两次? -
它几乎像 array_unique;这很可能是问题所在。
-
@Barmar 它用于过滤。我看到它删除了可能导致问题的重复值,但现在数组返回重复值。