PHP - 从对象数组的搜索结果中填充新数组

时间:2011-07-04 10:46:36

标签: php arrays

所有

我有一个像这样的Widget配置数组:

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

我有一个像这样的Widget对象数组:

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
                         ) 
)

对于Widget Config数组中的每个数组项,我需要搜索widgetId的Widget对象数组,如果找到它,我需要用找到的项创建一个新的Widget对象数组。

Ex:在Widget配置数组中搜索项目后创建的新Widget对象数组如下所示:

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
                         ) 
)

我如何通过PHP实现这一目标?

1 个答案:

答案 0 :(得分:1)

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