我正在尝试创建一个函数,它将获取一个数组并创建列和值,但我不知道如何返回带函数的引用。任何帮助表示赞赏。
private function data($data) {
$columns = "";
$values = array();
foreach ($data as $column => $value) {
$columns .= ($columns == '') ? '' : ', ';
$columns .= $column;
$values[$column] = &$data[$column];
}
return array($columns, $values);
}
这是在数据库中插入数据的功能。
/**
* Insert item into items table.
*
* @param (array) $data - Column => value array created in item class.
*/
public function insertItem($data) {
$columns = "";
$values = array();
$prep = "isiisiisiiis";
/*foreach ($data as $column => $value) {
$columns .= ($columns == '') ? '' : ', ';
$columns .= $column;
$values[$column] = &$data[$column];
}*/
$theData = $this->data($data);
$a = str_repeat('?, ', count($data) );
$b = substr_replace($a, '', -2);
$q = $this->db->mysqli->prepare("INSERT INTO items ($columns) VALUES ($b)");
call_user_func_array( array($q, 'bind_param'), array_merge(array($prep), $values) );
$q->execute();
$q->close();
//return id
return $this->db->mysqli->insert_id;
}
编辑**工作代码:
private function data(&$data) {
$columns = "";
$values = array();
foreach ($data as $column => $value) {
$columns .= ($columns == '') ? '' : ', ';
$columns .= $column;
$values[$column] = &$data[$column];
}
return array($columns, $values);
}
像这样访问它:
$theData = $this->data($data);
$theData[0]; //$columns
$theData[1]; //$values
答案 0 :(得分:0)
试试这个:在函数参数中添加&
并删除foreach循环中的&
。
private function data (&$data)
{
$columns = "";
$values = array ();
foreach ($data as $column => $value)
{
$columns .= ($columns == '') ? '' : ', ';
$columns .= $column;
$values[$column] = $data[$column];
}
return array ($columns, $values);
}
在公共函数insertItem中删除$theData =
public function insertItem ($data)
{
[..]
$this->data ($data);
}
答案 1 :(得分:0)
private function data(&$data) {
$columns = "";
$values = array();
foreach ($data as $column => $value) {
$columns .= ($columns == '') ? '' : ', ';
$columns .= $column;
$values[$column] = &$data[$column];
}
return array($columns, $values);
}
$theData = $this->data($data);
$theData[0]; //$columns
$theData[1]; //$values