Php 如何选择包含关联的字段作为主实体的字段?

Php 如何选择包含关联的字段作为主实体的字段?,php,arrays,rest,api,cakephp,Php,Arrays,Rest,Api,Cakephp,我在一个项目中使用了CakePHP3,我正在使用api rest获取JSON,以便在移动设备中获取数据。 我有两个与外键关联的表,如下所示: MySql tables ---------------------- Table Tickets: |id|code|price_id| Table Prices |id|price| ---------------------- 在TicketsTable CakePHP中: $this->belongsTo(

我在一个项目中使用了CakePHP3,我正在使用api rest获取JSON,以便在移动设备中获取数据。 我有两个与外键关联的表,如下所示:

  MySql tables 
  ----------------------
  Table Tickets:
  |id|code|price_id|

  Table Prices
  |id|price|

  ----------------------
在TicketsTable CakePHP中:

$this->belongsTo('Prices', [
        'foreignKey' => 'price_id',
        'joinType' => 'INNER'
    ]);
在控制器中,当我创建REST api时:

$this->loadModel('Tickets');
        $entradas = $this-> Tickets->find('all')
            ->contain('Prices')
            ->select(['Tickets.code','Prices.price'])
            ->limit('200')
            ->toArray();
然后,解析为JSON的数组返回以下内容:

"result":{  
      "tickets":[  
         {  
            "code":"08998112773",
            "prices":{  
               "prices.price":1
            }
         },
         {  
            "code":"07615265880",
            "prices.prices":{  .........
我想返回这个JSON:

   "result":{  
          "tickets":[  
             {  
                "code":"08998112773",
                "price":1
             },
             {  
                "code":"07615265880",
                "price":1  .........
也就是说,prices不会插入到新数组中,并且表名不会出现在字段名中

非常感谢

您可以使用创建新阵列:

$tickets = [
    'result' => [
        'tickets' => [
            [
                'code' => '123',
                'prices' => [
                    'prices.price' => '2'
                ]
            ],
            [
                'code' => '312423',
                'prices' => [
                    'prices.price' => '4'
                ]
            ]
        ]
    ]
];

$collection = new Collection($tickets['result']['tickets']);

$new = $collection->map(function ($value, $key) {
    return [
        'code' => $value['code'], 
        'price' => $value['prices']['prices.price']
    ];
});

$result = $new->toArray();

debug(json_encode(['result' => ['tickets' => $new]], JSON_PRETTY_PRINT)); 
die;
输出为:

{
    "result": {
        "tickets": [
            {
                "code": "123",
                "price": "2"
            },
            {
                "code": "312423",
                "price": "4"
            }
        ]
    }
}