HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Combining two arrays using nested foreach loops

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayscombiningloopsnestedtwousingforeach

Problem

I have the following arrays:

Array  (db_values)
(
[0] => Array
    (
        [system_name] => object_car_brand
        [value] => Alfa Romeo
        [id] => 136
    )

[1] => Array
    (
        [system_name] => object_car_model
        [value] => Spider
        [id] => 137
    )

)
Array (db_attributes)
(
[0] => Array
    (
        [id] => 105
        [system_name] => object_car_brand
    )

[1] => Array
    (
        [id] => 106
        [system_name] => object_car_model
    )

)


I combine these two using the following code:

foreach($db_attributes as $db_attribute){
            foreach($db_values as $db_value){
                if($db_value["system_name"] === $db_attribute["system_name"]){
                    $update[$db_attribute["id"]] = $db_value["value"];
                }

            }

        }


I do not think that this is the most resource friendly way of doing it, is there a better way?

Solution

I have made the assumption that there is a 1:1 relationships between the $attributes and $values array elements. With that I mean the array key in the $attributes array corresponds with an entry in $values array.

If that is the case it can be reduced to one foreach loop by using the key from the attributes array:

$combined = []; // Make sure the $combined array exists.

foreach($attributes as $key => $attribute) {

    // First check if the array key exists and that the 'system_name' is the same
    if(array_key_exists($key, $values) && $attribute['system_name'] == $values[$key]['system_name']) {

        $combined[$attribute['id']] = $values[$key]['value'];

    }

}


This should produce the following array with the data you have provided:

Array(combined)
(
    [106] => 'Alfa Romeo' 
)


If my assumption is incorrect, then just ignore my answer.

Code Snippets

$combined = []; // Make sure the $combined array exists.

foreach($attributes as $key => $attribute) {

    // First check if the array key exists and that the 'system_name' is the same
    if(array_key_exists($key, $values) && $attribute['system_name'] == $values[$key]['system_name']) {

        $combined[$attribute['id']] = $values[$key]['value'];

    }

}
Array(combined)
(
    [106] => 'Alfa Romeo' 
)

Context

StackExchange Code Review Q#70419, answer score: 3

Revisions (0)

No revisions yet.