如何递归查找次要配置文件并合并到主要配置文件中



我有一个示例数组,我想在其中找到次要的,并递归地检查次要的,直到所有次要的配置文件都从PHP数组中取消设置。以下是示例数组。

$testarray= array(
array(
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'abc,def,ghi',
'created_at' => '1546753453',
'profile_type' => 'primary'
),
array(
'id' => 'uisvuiacsiodciosd',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'def',
'created_at' => '1546753453',
'profile_type' => 'secondary'
),
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'ghi',
'created_at' => '1546753453',
'profile_type' => 'secondary'
)
),
array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'abc',
'created_at' => '1546753453',
'profile_type' => 'secondary'
),
array(
'id' => 'ccdbh-743748',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'abc,def',
'created_at' => '1546753453',
'profile_type' => 'primary'
)
),
array(
array(
'id' => 'sdcisodjcosjdocij',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'abc',
'created_at' => '1546753453',
'profile_type' => 'secondary'
),
array(
'id' => 'sdcisodjcoscisudhiu',
'name' => 'test',
'email' => 'testemail@test.com',
'newsletter' => 'abc,def',
'created_at' => '1515217453',
'profile_type' => 'primary'
)
)
);

到目前为止我已经尝试过了。

function duplicate_profiles_merger ($profiles_array) {
$innderdata = array();
foreach ($profiles_array as $key => $val) {
if (is_array($val) && in_array('secondary', $val)) {
unset($val[$key]);
// echo 'recursion';
duplicate_profiles_merger($profiles_array);
} else {
// $innderdata = $val;
//POST Request API code goes here. Like curl request.
//data '{"primary":{"email":"cool.person@company.com"}, "secondary":{"email":"cperson@gmail.com"}}'
echo 'done';
}

return $innderdata = $val;

}
}

但这让我处于一种无限的状态。下面是我想要实现的场景。

以下是我需要通过API发布请求传递的数据。数据"主":"电子邮件":";cool.person@company.com"次级":{"电子邮件":;cperson@gmail.com"}}'

现在我需要主电子邮件和辅助电子邮件进行配置文件合并。但是数组中存在不止一个辅助概要文件,因此,我需要某种递归功能。

感谢

这个答案总结了注释部分:

您使用与您开始使用的数组完全相同的数组来调用递归方法。但是PHP将参数作为默认值传递,这意味着您只修改$var元素,而不修改$profiles_array,因此您将创建一个无限循环。

加:这里不需要递归,因为这里没有"递归";子结构";这将从这里的真正递归中获利。一个简单的循环就可以了。

function duplicate_profiles_merger ($profiles_array) {
$innderdata = array();
foreach ($profiles_array as $key => $val) {
if (is_array($val) && $val['profile_type'] == 'primary') {
array_push($innerdata, $val);
}
}
return $innerdata;
}

这应该是它的全部。你也可以修改现有的数组,例如删除所有的辅助配置文件。然后,您必须将数组作为引用而非值传递:https://www.php.net/manual/en/language.references.pass.php

最新更新