3

我有一个 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;
}
}
4

1 回答 1

4

您的对象属性都是私有的——它们必须是公共的才能被 json_encode 访问。或者您需要从对象方法中调用 json_encode。

于 2012-05-07T17:40:03.820 回答