我有一个多维数组,其中一些值来自 foreach,我需要将这些值插入到数组中,但此时我的结果是这样的,不知道为什么: Array( [0] => Array ( [title] => MySecure ) [1] => Array ( [productTitle] => My New Product ) [2] => Array ( [title] => My Second Company ) [3] => Array ( [productTitle] => Another Product ) [4] => Array ( [productTitle] => Away Product ))这是错误的,我需要的是:Array( [0] => Array ( [title] => MySecure [productTitle] => My New Product ) [2] => Array ( [title] => My Second Company [productTitle] => Another Product [productTitle] => Away Product ) )这就是我所做的:$companies[] = [ 'title' => $getCompanie->getTitle() ];然后是里面的产品:$companies[] = [ 'productTitle' => $getProduct->getTitle(), ];所以我假设我使用了错误的数组调用,不确定 array_push?
2 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
您需要将两个键添加到同一个内部数组中,而不是单独推送它们。
使用嵌套循环在同一循环中获取与公司关联的所有产品。
$companies = [];
foreach ($all_companies as $companie) {
$products = [];
foreach ($companie->getProducts() as $getProduct) {
$products[] = $getProduct->getTitle());
}
$companies[] = [
'title' => $companie->getTitle(),
'productTitle' => $products
]
}
我不得不为我认为在你的代码中的一些东西命名。您应该能够由此推断出您的实际设计。
慕妹3146593
TA贡献1820条经验 获得超9个赞
$newArray= [
'title' => array_map($yourArray,fn($ar)=>$ar['title']),
'productTitle' => array_map($yourArray,fn($ar)=>$ar['productTitle'])
];
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消