Search code examples
phparraysassociative-array

Match array items value and assign new value to associative array


I have an associative array with multiple array items in PHP, in which some array items have specific values like ccdbh-743748 and some have not. I needed to check by running a loop on this array that if any array item has this value ccdbh-743748, then add a new key to that array item like this 'profile_type' => 'primary'. and if there is no matching value on another array item then add a new key to that array item like this. 'profile_type' => 'secondary'

Here is the array structure.

0 => array(
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => '[email protected]'
    ),
    array(
        'id' => 'uisvuiacsiodciosd',
        'name' => 'test',
        'email' => '[email protected]'
    ),
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => '[email protected]'
    )
),
1 => array(
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => '[email protected]'
    ),
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => '[email protected]'
    )
)

I want the result should be like this

0 => array(
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => '[email protected]'
        'profile_type' => 'primary'
    ),
    array(
        'id' => 'uisvuiacsiodciosd',
        'name' => 'test',
        'email' => '[email protected]'
        'profile_type' => 'secondary'
    ),
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => '[email protected]'
        'profile_type' => 'secondary'
    )
),
1 => array(
    array(
        'id' => 'sdcisodjcosjdocij',
        'name' => 'test',
        'email' => '[email protected]'
        'profile_type' => 'secondary'
    ),
    array(
        'id' => 'ccdbh-743748',
        'name' => 'test',
        'email' => '[email protected]',
        'profile_type' => 'primary'
    )
)

Any progressive workaround for this query, either with pre-built in PHP functions or some custom solution for this.


Solution

  • There are probably more elegant ways to go about this, but you can just use a couple foreach loops...

    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);
    

    Example: https://tehplayground.com/s5QTv7QfBde6V8pi