匹配数组项值并将新值分配给关联数组

Match array items value and assign new value to associative array

我在 PHP 中有一个包含多个数组项的关联数组,其中一些数组项具有特定值,例如 ccdbh-743748,而另一些则没有。 我需要通过 运行 循环检查此数组是否有任何数组项具有此值 ccdbh-743748,然后向该数组项添加一个新键,如下所示 'profile_type' => 'primary' . 如果另一个数组项没有匹配值,则像这样向该数组项添加一个新键。 'profile_type' => 'secondary'

这里是数组结构

0 => array(
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => 'testemail@test.com'
    ),
    array(
        'id' => 'uisvuiacsiodciosd',
        'name' => 'test',
        'email' => 'testemail@test.com'
    ),
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => 'testemail@test.com'
    )
),
1 => array(
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => 'testemail@test.com'
    ),
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => 'testemail@test.com'
    )
)

I want the result should be like this

0 => array(
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => 'testemail@test.com'
        'profile_type' => 'primary'
    ),
    array(
        'id' => 'uisvuiacsiodciosd',
        'name' => 'test',
        'email' => 'testemail@test.com'
        'profile_type' => 'secondary'
    ),
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => 'testemail@test.com'
        'profile_type' => 'secondary'
    )
),
1 => array(
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => 'testemail@test.com'
        'profile_type' => 'secondary'
    ),
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => 'testemail@test.com',
        'profile_type' => 'primary'
    )
)

此查询的任何渐进式变通方法,可以使用预置的 PHP 函数或一些自定义解决方案。

可能有更优雅的方法来解决这个问题,但您可以只使用几个 foreach 循环...

foreach( $source as $sub ){
    $newsub=[];
    foreach ($sub as $item) {
        $p = ($item['id']==='ccdbh-743748') ? 'primary' : 'secondary';
        $item['profile_type']=$p;
        $newsub[]=$item;
    }
    $newsource[]=$newsub;
}

print_r($newsource);

示例:https://tehplayground.com/s5QTv7QfBde6V8pi