2013-12-15 20 views
0

我试图合并一组来自不同对象的数组。可以说,我有这样的设置:合并多个数组而不覆盖第一个找到的值

class Base { 
    static $defaults = array (
     'time' => 'DEFAULT', 
     'color' => 'DEFAULT', 
     'friend' => 'DEFAULT', 
     'pub' => 'DEFAULT', 
     'money' => 'DEFAULT', 
    ); 
    static function isDefault ($key, $value) {} 
    $properties; 
} 
class A extends Base { 
    function __construct() { 
     $data = array('time' => '6pm', 'friend' => 'Jack'); 
     $this->properties = array_merge(self::$defaults, $data); 
    }; 
class B extends Base { 
    function __construct() { 
     $data = array('pub' => 'The Lion', 'friend' => 'Jane'); 
     $this->properties = array_merge(self::$defaults, $data); 
    }; 
} 
class C extends Base { 
    function __construct() { 
     $data = array('money' => 'none', 'pub' => 'Queens'); 
     $this->properties = array_merge(self::$defaults, $data); 
    }; 
} 
$sequence = array(new A, new B, new C); 

我所知道的是,对象是在序列和存在所谓properties的数组。我想合并这些阵列,使结果如下所示:

array (
    'time' => '6pm', 
    'color' => 'DEFAULT', 
    'friend' => 'Jack', 
    'pub' => 'The Lion', 
    'money' => 'none', 
) 

我想要第一个没有默认值存储。什么是做这个的快速方法?

+0

什么是在这种奇怪的方式控制您的设置感?为什么你想要新的实例化来改变整个上下文?很难理解(即使你的简短示例代码,我需要几分钟的时间才能意识到发生了什么) –

+0

@AlmaDo它是插件系统的一部分,容器需要知道其包含的组中的有效回调。而不是调用每个实例,我想在初始化时构建数组。 – Twifty

回答

1

步骤1:定义ISDEFAULT

static function isDefault ($key, $value) { 
    return($value == self::$defaults[$key]); 
} 

步骤2:环。

<?php 
$result = array(); 
foreach($sequence AS $object){ 
    foreach($object->properties AS $key=>$value){ 
     if(!isset($result[$key]) || Base::isDefault($key, $result[$key])){ 
      $result[$key] = $value; 
     } 
    } 
} 
var_dump($result); 

小提琴:http://phpfiddle.org/main/code/anh-hrc

结果为:

array(5) { 
    ["time"]=> string(3) "6pm" 
    ["color"]=> string(7) "DEFAULT" 
    ["friend"]=> string(4) "Jack" 
    ["pub"]=> string(8) "The Lion" 
    ["money"]=> string(4) "none" 
} 
+0

工程很棒。谢谢:) – Twifty

+0

我的荣幸:)是一个整洁的挑战。 – Jessica

相关问题