如何从包含不同值的两个数组中生成一个数组



我有两个数组,一个叫做fetched_services,一个叫fetched_companies,它们看起来像这样:

fetched_services

(
[1] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 153
)
[1] => Array
(
[id] => 137
)
[2] => Array
(
[id] => 138
)
)
)
)

已提取公司

(
[0] => stdClass Object
(
[services] => Array
(
[0] => 25
[1] => 102
)
)
)

我想要实现的是最终得到一个像fetched_services一样的数组,但只有id为fetched_companies["services"]child_services

我试过的是:

$services = [];
$isFound = false;
foreach ($fetched_services as $fetched_service) {
foreach ($fetched_service["child_services"] as $fetched_child_service) {
$fetched_service["child_services"] = [];
foreach ($fetched_companies as $fetched_company) {
if( (in_array($fetched_child_service["id"],$fetched_company->services)) ) {
$fetched_service["child_services"][] = $fetched_child_service;
$isFound = true;
}
}
if($isFound) {

$services[] = $fetched_service;
$isFound = false;
}
}
}

此输出为:

Array
(
[0] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 116
)
)
)
[1] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 117
)
)
)
)

正如您所看到的,生成的数组有两个包含相同id的数组,但child_services不同。

我最终想要的是:

Array
(
[0] => Array
(
[id] => 11
[child_services] => Array
(
[0] => Array
(
[id] => 116
)
)
(
[0] => Array
(
[id] => 117
)
)
)
)

我在这里做错了什么?谢谢

您的问题有点不清楚(如果/当您澄清时,我会编辑/删除它,请参阅我上面的评论(,但您可能可以通过只保留所述列表中存在的服务(通过in_array(来使用array_filter

$result = array_filter(
$fetched_services['child_services'],
fn(array $child_service): bool => in_array($child_service['id'], $fetched_companies[0]->services, true)
);

演示

相关内容

  • 没有找到相关文章

最新更新