简体   繁体   中英

PHP - Populate new array from search result of array of objects

All,

I have a Widget Config array like this:

Array 
( 
[0] => Array ( [0] => 1 [1] => apple ) 
[1] => Array ( [0] => 1 [1] => orange ) 
[2] => Array ( [0] => 2 [1] => banana)
)

I have an array of Widget Objects like this:

Array 
( 
[0] => XYZ_Widget Object ( 
                           [position:XYZ_Widget:private] => 1 
                           [widgetId:XYZ_Widget:private] => apple 
                         ) 
[1] => XYZ_Widget Object ( 
                           [position:XYZ_Widget:private] => 2 
                           [widgetId:XYZ_Widget:private] => banana 
                         ) 
[2] => XYZ_Widget Object (  
                           [position:XYZ_Widget:private] => 3 
                           [widgetId:XYZ_Widget:private] => orange
                         ) 
)

For each array Item in Widget Config array, I need to search the array of Widget Objects for widgetId and if it's found, I need to create a new Array of Widget Objects with the found items.

Ex: The new array of Widget Objects created after searching for items in Widget Config array will look like:

Array 
( 
[0] => XYZ_Widget Object ( 
                           [position:XYZ_Widget:private] => 1 
                           [widgetId:XYZ_Widget:private] => apple 
                         ) 
[1] => XYZ_Widget Object ( 
                           [position:XYZ_Widget:private] => 3 
                           [widgetId:XYZ_Widget:private] => orange 
                         ) 
[2] => XYZ_Widget Object (  
                           [position:XYZ_Widget:private] => 2 
                           [widgetId:XYZ_Widget:private] => banana
                         ) 
)

How do I do this through PHP?

$result = array();
foreach ($configuration as $widgetConf) {
    foreach ($widgets as $widget) {
        if ($widgetConf[1] == $widget->widgetId) {
            $result[] = $widget;
            continue 2;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM