我正在创建一个泛型函数来在一个公共属性的数组中推送键值对。
当我调用pushDetailsToArray函数时,在getHospitalDetails函数内部似乎没有填充公共属性数组。虽然当您尝试在pushDetailsArray函数内打印数组时,它会打印出来。有谁知道我在这里做错了什么?提前谢谢。
public function pushDetailsToArray($row, $array){
foreach($row as $key => $value){
$array[$key] = $value;
}
//print_r($this->hospDetails);
return $array;
}
public function getHospDetails(){
$row = $this->queryThis( "SELECT * from tblhospitals WHERE HospID = '$this->sessionId'" );
/*foreach($row as $key => $value){
$this->hospDetails[$key] = $value;
}*/
$this->pushDetailsToArray($row, $this->hospDetails);
print_r($this->hospDetails);
}
顺便说一句,getHospitalDetails方法中注释掉的foreach循环有效。我只是希望能够制作一个循环的通用方法。
答案 0 :(得分:0)
如果您确定要引用用户,可以将pushDetailsToArray
更改为:
<?php
public function pushDetailsToArray($row, &$array)
{
foreach($row as $key => $value)
{
$array[$key] = $value;
}
}
然后像这样调用它(phpversion&gt; = 5.3)
$this->pushDetailsToArray($row, $this->hospDetails);
或(phpversion&lt; 5.3):
$this->pushDetailsToArray($row, &$this->hospDetails);
-
********** But, I suggest not to use `reference` **************
您只需将pushDetailsToArray
更改为:
<?php
public function pushDetailsToArray($row)
{
$array = array();
foreach($row as $key => $value)
{
$array[$key] = $value;
}
return $array;
}
然后:
$this->hospDetails = $this->pushDetailsToArray($row);
答案 1 :(得分:0)
public function pushDetailsToArray($row){
$array=array();
foreach($row as $key => $value){
$array[$key] = $value;
}
//print_r($this->hospDetails);
return $array;
}
public function getHospDetails(){
$row = $this->queryThis( "SELECT * from tblhospitals WHERE HospID = '$this->sessionId'" );
/*foreach($row as $key => $value){
$this->hospDetails[$key] = $value;
}*/
$this->hospDetails=$this->pushDetailsToArray($row);
print_r($this->hospDetails);
}
答案 2 :(得分:0)
也许我错过了什么,但你为什么不这样做:
public function getHospDetails(){
$row = $this->queryThis( "SELECT * from tblhospitals WHERE HospID = '$this->sessionId'" );
$this->hospDetails = $row;
}
除非$row
不是数组,否则选项2。
public function pushDetailsToArray($row) {
$output = array();
foreach($row as $key => $value){
$output[$key] = $value;
}
return $output;
}
public function getHospDetails() {
$row = $this->queryThis( "SELECT * from tblhospitals WHERE HospID = '$this->sessionId'" );
$this->hospDetails = $this->pushDetailsToArray($row);
}
public function pushRowToHospDetails($row) {
foreach($row as $key => $value){
$this->hospDetails[$key] = $value;
}
return $this
}
public function getHospDetails() {
$row = $this->queryThis( "SELECT * from tblhospitals WHERE HospID = '$this->sessionId'" );
$this->pushRowToHospDetails($row);
}