将Php数组传递给JSON

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;
}
}

1
var_dump($return); 输出什么? - Paul
@PaulP.R.O. var_dump($return); 显示了创建的整个数组,而且所有显示的值都是正确的。 - Frab Lopez
@TheOx 类 $class 的所有方法和属性都是公共的。而且 $class 是一个对象。 - Frab Lopez
这个$class对象有什么属性吗?请展示$class的定义。 - Shiplu Mokaddim
@Fran - 你能发布 var_dump 输出吗? - TheOx
显示剩余4条评论
1个回答

4

您的对象属性都是私有的 - 它们需要是公共的才能被json_encode访问。或者您需要在对象方法内调用json_encode。


@TheOnyx 非常感谢,我私有属性那里弄错了,谢谢你,现在它可用了。 - Frab Lopez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接