我无法将 PHP对象转换为数组,并将其作为对象发送到 JavaScript文件。 这是我正在做的事情: 从数据库获取用户对象 - 它看起来像这样:
Array
(
[0] => AppBundle\AdminBundle\Entity\AdminUser Object
(
[id:protected] => 1
[name:protected] => Kamil
[surname:protected] => Stangelj
[birthdate:protected] => DateTime Object
(
[date] => 1996-01-28 00:00:00.000000
[timezone_type] => 3
[timezone] => Europe/Berlin
)
[email:protected] => kamiltomice@gmail.com
[login:protected] => Sztanga
[password:protected] => $2y$15$qyD9tbeIcXqRKTQeUJEiLehWo16XKy447NVWU7q/VyvYSD0k61f6C
[image:protected] => resources_admin/images/upload/users/1510092373jDuHxJkOnGp1RNxTOy0OBez nazwy-1.png
[role:protected] => ["1","2","3","4","5","6","7","8","9","10"]
[lock_date:protected] => DateTime Object
(
[date] => 2017-12-17 15:20:08.000000
[timezone_type] => 3
[timezone] => Europe/Berlin
)
[is_active:protected] => 1
[is_non_locked:protected] => 1
[lock_info:protected] =>
)
)
我正在做的另一个步骤是通过object_to_array函数(来自that example的this Stack answer转换它 - 这个答案对我没有帮助)。这是上面链接中的功能:
public function objectToArray($data)
{
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = UsefulController::objectToArray($value);
}
return $result;
}
return $data;
}
这是一个问题,因为该函数返回一个空数组:
Array
(
[0] => Array
(
)
)
如果有人不明白我的问题。我想将我首先指向的PHP对象转换为数组并将其传递回我的JavaScript文件,将其存储为对象。
非常简单:
输入数据: PHP对象
输出数据: JavaScript对象
答案 0 :(得分:0)
这个json_encode()
答案 1 :(得分:0)
我认为AdminUser实体应该有gatter和setter方法。你必须为此手动创建php关联数组。喜欢
array('id'=> $ user-> getId());
然后使用json_decode将其转换为json字符串。
答案 2 :(得分:0)
解决它的唯一方法是创建一个数组并对其进行编码然后发送..
$result['id'] = $user->getId();
$result['name'] = $user->getName();
$result['surname'] = $user->getSurname();
$result['birthdate'] = $user->getBirthdate()->format('d-m-Y');
$result['email'] = $user->getEmail();
$result['login'] = $user->getLogin();
$result['image'] = $user->getImage();
$result['role'] = $user->getRole();
$result['is_active'] = $user->getIsActive();
$result['is_non_locked'] = $user->getIsNonLocked();
$result['lockdate'] = $lockdate;
$result['lockinfo'] = $user->getLockinfo();