如何获取对象属性(数组集合)?

时间:2019-01-07 16:55:26

标签: php arrays json symfony object

这是我的对象ALTER USER ANONYMOUS ACCOUNT UNLOCK

products

当我这样创建json文件时...

array:1 [▼
  0 => Products {#8662 ▼
    -id: 5
    -name: "lion"
    -unique_id: "7726d59574"
    -productgroup: PersistentCollection {#8763 ▼
      -snapshot: array:2 [ …2]
      -owner: Products {#8662}
      -association: array:20 [ …20]
      -em: EntityManager {#4326 …11}
      -backRefFieldName: null
      -typeClass: ClassMetadata {#8294 …}
      -isDirty: false
      #collection: ArrayCollection {#8666 ▼
        -elements: array:2 [▼
          0 => Productgroup {#8765 ▼
            -id: 5
            -name: "Mammals"
            -unique_id: "12102400f9"
          }
          1 => Productgroup {#8769 ▼
            -id: 7
            -name: "Fish"
            -unique_id: "f0fbfa5c19"
          }
        ]
      }
      #initialized: true
    }
  }
]

...我得到这个结果:

$result = $serializer->serialize($products, 'json');

但是我需要的结果只是产品组。所以这就是我想要达到的目的:

[{"id":5,"uniqueId":"7726d59574","name":"lion","productgroup":[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]}]

这是我的第一种方法:

[{"id":5,"uniqueId":"12102400f9","name":"Mammals"},{"id":7,"uniqueId":"f0fbfa5c19","name":"Fish"}]

但是我收到了错误消息:

  

注意:试图获取非对象的属性“产品组”

我认为,好吧,这意味着$data = $products->productgroup; $result = $serializer->serialize($data, 'json'); 不是对象,所以我尝试了这一点:

products

但是现在我得到了错误:

  

不能将App \ Entity \ Products类型的对象用作数组

1 个答案:

答案 0 :(得分:1)

尝试使用类似这样的内容:

import childs1 from '@/router/modules/childs1'
export default new Router({
  routes: [
    {
      path: '/main',
      name: 'main',
      component: mainComponent,
      children: chids1
    }
  ]

//childs1.js
import childs2 from '@/router/modules/childs2'
export default [
  {
    path: 'sub1',
    name: 'sub1',
    component: sub1,
    children: chids2
  }
]

//childs2.js
import childs3 from '@/router/modules/childs3'
export default [
  {
    path: 'sub2',
    name: 'sub2',
    component: sub2,
    children: chids3
  }
]

//childs3.js
export default [
  {
    path: 'final',
    name: 'final',
    component: finalComponent
  }

方法foreach ($products as $product) { $data = $product->getProductGroup(); } 必须存在于您的实体中,否则,您可能会有类似的想法。