Eduardorph Eduardorph - 1 month ago 5
PHP Question

Add a value from one array to another when they have an equal specific value

I have these two arrays:

$ar1 = array(
0 => array(
'name' => 'MIRIAN',
'total' => '34'
),
1 => array(
'name' => 'THIAGO',
'total' => '29'
),
2 => array(
'name' => 'EDUARDO',
'total' => '3'
)
);


$ar2 = array(
0 => array(
'operator' => 'THIAGO',
'totalop' => '703'
),
1 => array(
'operator' => 'MIRIAN',
'totalop' => '180'
)

);


And i want to create a third like this, but i don't know what should i do:

$ar3 = array(
0 => array(
'name' => 'MIRIAN',
'total' => '34'
'totalop' => '180'

),
1 => array(
'name' => 'THIAGO',
'total' => '29',
'totalop' => '703'
),
2 => array(
'name' => 'EDUARDO',
'total' => '3'
)
);


What is the best way to do this, I tried many ways, but without success?

Thanks for any help

Answer

Solution:

$ar1 = array(
    0 => array(
        'name' => 'MIRIAN',
        'total' => '34'
    ),
    1 => array(
        'name' => 'THIAGO',
        'total' => '29'
    ),
    2 => array(
        'name' => 'EDUARDO',
        'total' => '3'
    )
);


$ar2 = array(
    0 => array(
        'operator' => 'THIAGO',
        'totalop' => '703'
    ),
    1 => array(
        'operator' => 'MIRIAN',
        'totalop' => '180'
    )

);


$index = [];
$ar1Key = 'name';
$ar2Key = 'operator';

foreach ($ar1 as $item) {
    $index[$item[$ar1Key]] = $item;
}

foreach ($ar2 as $item) {
    $pk = $item[$ar2Key];

    unset($item[$ar2Key]);

    if (isset($index[$pk])) {
        $index[$pk] = array_merge($index[$pk], $item);
    } else {
        $index[] = $item;
    }
}

$ar3 = array_values($index);

print_r($ar3);