Php 将对象转换为数组
我添加了一个函数,用于将父子列表转换为“city”类的对象: 现在我想创建一个函数来执行相反的=>将一个类型为Class City的对象转换为数组,所以我喜欢这样:Php 将对象转换为数组,php,symfony,Php,Symfony,我添加了一个函数,用于将父子列表转换为“city”类的对象: 现在我想创建一个函数来执行相反的=>将一个类型为Class City的对象转换为数组,所以我喜欢这样: public function getCityArray(City$rootCity) { $result = array(); $result['id'] = $rootCity->getId(); $result['label']= $rootCity->get
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)然后语法可能会出错。我甚至不知道PHP是否有多维数组。我可能只是看错了,我是PHP的业余爱好者。
$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);
}
}
}