Home > Net >  How can I substitute the values of an associative array with a unique value in the same array?
How can I substitute the values of an associative array with a unique value in the same array?

Time:11-26

Hopefully, this should be quite simple, but I just can't figure out how to go about it. I have an array like so:

$array = [
    ['record' => 1, 'sponsor' => 2, 'email' => '[email protected]'],
    ['record' => 2, 'sponsor' => 2, 'email' => '[email protected]'],
    ['record' => 3, 'sponsor' => 2, 'email' => '[email protected]'],
    ['record' => 4, 'sponsor' => 2, 'email' => '[email protected]'],
];

Each row has a unique record and email and the sponsor key is related to the record. So, instead of an integer, I am trying to replace the value of the sponsor key with the corresponding email based on the record, something like this:

$array = [
    ['record' => 1, 'sponsor' => '[email protected]', 'email' => '[email protected]'],
    ['record' => 2, 'sponsor' => '[email protected]', 'email' => '[email protected]'],
    ['record' => 3, 'sponsor' => '[email protected]', 'email' => '[email protected]'],
    ['record' => 4, 'sponsor' => '[email protected]', 'email' => '[email protected]'],
];

I have tried using a foreach loop but it doesn't give me the expected result:

$yes = [];
foreach ($array as $key => $arr) {
    if ( ! empty($arr['sponsor']) ) {
        if ( $arr['sponsor'] == $array[$key]['record'] ) {
            $yes[] = ['sponsor' => $array[$key]['email']];
        }
    }
    $yes[] = [
        'record' => $array[$key]['record'], 
        'email' => $array[$key]['email'],
        'sponsor' => $array[$key]['sponsor'],
    ];
}
print_r($yes);

CodePudding user response:

As record is unique, I recommend rebuilding $arr using this value as the key. Then you loop again to replace your value for $sponsor

$indexedArray = [];
foreach ($array as $v) {
  $indexedArray[$v['record']] = $v;
}   
foreach ($indexedArray as $record => $v) {
  if (isset($indexedArray[$v['sponsor']]) && isset($indexedArray[$v['sponsor']]['email'])) {
    $indexedArray[$record]['sponsor'] = $indexedArray[$v['sponsor']]['email'];
  }
}
$yes = array_values($indexedArray);
  • Related