jeudi 22 mars 2018

Replacing values in an array basing on values from another

Having the 2 following arrays:

[
    {"id":1,"value":40},
    {"id":2,"value":30},
]

And:

[
    {"userId":1,"worth":20},
    {"userId":2,"worth":10},
]

What I want to have in the end, is the following result:

[
    {"id":1,"value":20},
    {"id":2,"value":10},
]

So here, I want to replace in the first array, the values with those in the second array, according to the ìd`. I made something like that:

foreach ($array2 as $k => $v) {
    array_filter($array1), function($item) use($value) {
        $item['id'] == $v['userId'] ? $item['value'] = $v['worth'] :$item['value'] = $item['value'];
    });
}

It is working for those given arrays, but if you have arrays with more than 1 million data, it will never be done ! The question is, if there are some PHP functions which can do this hard work?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire