PHP How To Merge An Array Of Objects WIth An Array Of Arrays

前端 未结 1 390
臣服心动
臣服心动 2021-01-14 22:26

First, sorry for the lengthly explanation. I have two arrays in PHP. The first array is an array of objects. The second array is an array of arrays. Basically, I want to loo

相关标签:
1条回答
  • 2021-01-14 22:56

    If you could index the array by gear or some unique value, it would be a lot easier.

    $indexed = array();
    
    // create an array using 'gear' as the index
    foreach($arrayValue as $value) {
        $indexed[$value['gear']] = $value;
    }
    
    // loop over each object
    foreach($objectArray as $obj) {
        $value = $indexed[$obj->gear]; // find the corresponding array
        foreach($value as $name => $val) {
            $obj->$name = $val; // assign each array index/value pair to the object
        }
    }
    

    If possible to get your code to return the array with the index by default, you can remove the first foreach loop.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题