Hash ::提取关联数据

时间:2014-05-08 09:43:08

标签: php cakephp associative

我有一个看起来像的数组:

array(
    0 => array (
        "Something" => array(
            "id" => 1,
            "foo" => "bar"
        ),
        "User" => array( ... )
    ),
    1 => array (
        "Something" => array(
            "id" => 5,
            "foo" => "foobar"
        ),
        "User" => array( ... )
    ),
    2 => array (
        "Something" => array(
            "id" => 13,
            "foo" => "bar"
        ),
        "User" => array( ... )
    )
)

我想提取“Something”,其中“foo”=“bar”bzt我也希望获得相关用户。 所以输出应该如下所示:

array(
    0 => array (
        "Something" => array(
            "id" => 1,
            "foo" => "bar"
        ),
        "User" => array( ... )
    ),
    1 => array (
        "Something" => array(
            "id" => 13,
            "foo" => "bar"
        ),
        "User" => array( ... )
    )
)

我试过了:

{n}.Something[foo=bar]  
{n}.Something[foo=bar]..  
{n}[Something.foo=bar]  
{n}[foo=bar]  
{n}.[Something.foo=bar]  
{n}.[foo=bar]  

用所有邻居提取数组的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

这有效:

array_filter(array_map(function($c) { if ($c['Something']['foo'] == 'bar') return $c; }, $YOURARRAY));

<强>更新 其他方法(如果你愿意的话,OOP方式)将使用FilterIterator(PHP 5&gt; = 5.1.0)可能有点矫枉过正,但可以胜任。 只需更改构造函数并接受调整数据的方法(目前它适用于您提供的数组)

class MyArrFilter extends FilterIterator 
{
    private $filterValue;
    private $filterFirstKey;
    private $filterSecondKey;

    public function __construct(Iterator $iterator, $filterFirstKey, $filterSecondKey, $filterValue)
    {
        parent::__construct($iterator);
        $this->filterValue = $filterValue;
        $this->filterFirstKey = $filterFirstKey;
        $this->filterSecondKey = $filterSecondKey;
    }

    public function accept()
    {
        $arr = $this->getInnerIterator()->current();
        if (isset($arr[$this->filterFirstKey][$this->filterSecondKey]) && 
            $arr[$this->filterFirstKey][$this->filterSecondKey] === $this->filterValue) {
            return true;
        }
        return false;
    }
}

$object = new ArrayObject($arr);
$iterator = new MyArrFilter($object->getIterator(), 'Something', 'foo', 'bar');

foreach ($iterator as $result) {
    var_dump($result);
}