我有下面的代码,从中我得到下面的数据响应..
public function getCategory(){
$this->autoRender = False;
$list = TableRegistry::get('Subproducts');
$supplierId = $this->request->data['supplierId'];
if($this->request->is('ajax')) {
if(!empty($supplierId)) {
$query1 = $list->find()->contain(['Products'])
->where(['Subproducts.supplier_id =' => $supplierId]);
$data = $query1->hydrate(false)->toArray();
if(!empty($data)){
**Print_r($data);**
**foreach ($data as $value){
print_r($value);
}**
//echo json_encode(array("category"=>$newArray));
exit;
}
}
}
}
下面的数据我是从上面的代码
Array
(
[supplier_id] => 40
[product] => Array
(
[id] => 45
[name] => PLASTIC ITEM
[is_deleted] => 0
)
)
Array
(
[supplier_id] => 40
[product] => Array
(
[id] => 50
[name] => RAW MATERIAL
[is_deleted] => 0
)
)
我想收集Id和产品数组名称在$newArray,但我不能迭代产品数组,不知道如何添加id和名称的产品在$newArray。谁能帮我迭代产品数组值,并创建只包含Id和Name的新数组。
我需要内部的帮助来迭代值,并创建只有id和产品数组名称的新数组。
**Print_r($data)是低于数据,我已经添加了Print_r($data);就像下面的代码一样,我的意思是在foreach循环之前…
if(!empty($data)){
print_r($data);
foreach ($data as $value) { }
}
Array
(
[0] => Array
(
[id] => 468
[supplier_id] => 40
[buy_price] => 6.23
[sell_price] => 7.87
[category_id] => 45
[product_name] => test1
[is_deleted] => 0
[created] => CakeI18nFrozenTime Object
(
[date] => 2021-10-12 09:48:20.000000
[timezone_type] => 3
[timezone] => UTC
)
)
[1] => Array
(
[id] => 469
[supplier_id] => 40
[buy_price] => 44.89
[sell_price] => 7.87
[category_id] => 50
[product_name] => test
[is_deleted] => 0
[created] => CakeI18nFrozenTime Object
(
[date] => 2021-10-12 11:44:28.000000
[timezone_type] => 3
[timezone] => UTC
)
)
)
循环遍历内部数组并从中获取您感兴趣的部分
UPDATE: Ok所以看起来数组不在另一个数组内所以一个简单的foreach就能做到
$newArray = []; // initialise the array
foreach ($data as $inner) {
$newArray[] = [ 'id' => $inner['product']['id'],
'name' => $inner['product']['name']
]
}
$newArray = []; // initialise the array
foreach ($data as $key=> $value) {
$newArray[] = [
'id' => $value['product']['id'],
'name' => $value['product']['name']
];
}