Skip to content
Advertisement

Substitute column value in each row of a 2d array based on other rows in the same array

I have an array like so:

$array = [
    ['record' => 1, 'sponsor' => 2, 'email' => 'some@email.com'],
    ['record' => 2, 'sponsor' => 2, 'email' => 'some1@email.com'],
    ['record' => 3, 'sponsor' => 2, 'email' => 'some2@email.com'],
    ['record' => 4, 'sponsor' => 2, 'email' => 'some3@email.com'],
];

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' => 'some1@email.com', 'email' => 'some@email.com'],
    ['record' => 2, 'sponsor' => 'some1@email.com', 'email' => 'some1@email.com'],
    ['record' => 3, 'sponsor' => 'some1@email.com', 'email' => 'some2@email.com'],
    ['record' => 4, 'sponsor' => 'some1@email.com', 'email' => 'some3@email.com'],
];

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement