PHP将数组传递给JSON
作者:互联网
我有一个PHP文件,该文件使用array_push创建类的数组,并且需要将此数组转换为JSON格式.
该数组创建完美,但是当我尝试编码为JSON时,返回的值是一个空元素数组.
的PHP代码:
$return = array();
if($_GET['action'] == 'loadImg'){
$id = $_GET['idAct'];
$class = $var->selectActById($id);
$list = $class->getImatgesAct();
for($i = 0; $i < sizeof($list);$i++){
$class = $var->findimatge($list[$i]->getIdBibl());
array_push($return, $class);
}
}
echo json_encode($return,true);
JSON返回的值是:
[{},{}]
谢谢
已编辑
var_dump:
array
0 =>
object(imatgeclass)[4]
private 'idimatge' => string '1' (length=1)
private 'nomimatge' => string 'hydra' (length=5)
private 'urlimatge' => string 'biblioimg/2012-05-06-23-19-17.jpg' (length=33)
1 =>
object(imatgeclass)[3]
private 'idimatge' => string '2' (length=1)
private 'nomimatge' => string 'pen' (length=3)
private 'urlimatge' => string 'biblioimg/2012-05-06-23-19-36.jpg' (length=33)
类的定义:
class imatgeclass{
private $idimatge, $nomimatge, $urlimatge;
public function setData($idimatge,$nomimatge,$urlimatge){
$this->idimatge = $idimatge;
$this->nomimatge = $nomimatge;
$this->urlimatge = $urlimatge;
}
public function getIdImatge(){
return $this->idimatge;
}
public function setIdImatge($idimatge){
$this->idimatge = $idimatge;
}
public function getNomImatge(){
return $this->nomimatge;
}
public function setNomImatge($nomimatge){
$this->nomimatge = $nomimatge;
}
public function geturlimatge(){
return $this->urlimatge;
}
public function setUrlImatge($urlimatge){
$this->urlimatge = $urlimatge;
}
}
解决方法:
您的对象属性都是私有的-它们必须是公共的,以便json_encode可以访问.或者您需要从一个对象方法中调用json_encode.
标签:array-push,json,php 来源: https://codeday.me/bug/20191101/1983029.html