Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将对象转换为数组_Php_Symfony - Fatal编程技术网

Php 将对象转换为数组

Php 将对象转换为数组,php,symfony,Php,Symfony,我添加了一个函数,用于将父子列表转换为“city”类的对象: 现在我想创建一个函数来执行相反的=>将一个类型为Class City的对象转换为数组,所以我喜欢这样: public function getCityArray(City$rootCity) { $result = array(); $result['id'] = $rootCity->getId(); $result['label']= $rootCity->get

我添加了一个函数,用于将父子列表转换为“city”类的对象:

现在我想创建一个函数来执行相反的=>将一个类型为Class City的对象转换为数组,所以我喜欢这样:

   public function getCityArray(City$rootCity)
{
        $result = array();

        $result['id'] = $rootCity->getId();
        $result['label']= $rootCity->getLabel();

    $children = $rootCity->getChildren();


    if ( !empty($children)) {
        foreach ($children as $key_child => $child) {

            $result['childrens'] = array($key_child => $child );

            $result[] = $this->getCityArray($child);
        }
    }

    return $result;

}

但它不起作用,因为当我执行var_dump(“$result”)时,我有一个没有结束的列表,循环不会停止?

试试这个。因为我不知道是否有完整的代码,所以不确定它是否能工作。类变量
$result
将包含结果

$result = array();
public function getCityArray(City $rootCity) {

  $result['id'] = $rootCity->getId();
  $result['label']= $rootCity->getLabel();
  $children = $rootCity->getChildren();

  if ( !empty($children)) {
    $result['childrens'] = $children;
    $this->result[] = $result;
    foreach ($children as $key_child => $child) {
      $this->getCityArray($child);
    }
  }

}

看起来您正在尝试将数组插入数组索引。这是否正确
$result['childrens']=array($key\u child=>$child)
看起来这可能会给你带来麻烦。那么停止递归的好条件是什么呢?除非你声明一个多维(我知道拼写)数组,否则我认为你不能做
$result['childrens']=array($key\u child=>$child)$result = array();
public function getCityArray(City $rootCity) {

  $result['id'] = $rootCity->getId();
  $result['label']= $rootCity->getLabel();
  $children = $rootCity->getChildren();

  if ( !empty($children)) {
    $result['childrens'] = $children;
    $this->result[] = $result;
    foreach ($children as $key_child => $child) {
      $this->getCityArray($child);
    }
  }

}