Question

I have an Array that looks like:

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

I want to extract alle "Something"s where "foo" = "bar" bzt I also want to get the assosiated User as well. So the output should look like this:

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

I tried:

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

What is the right way to extract an array with all its neighbor?

Was it helpful?

Solution

this works:

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

UPDATE: Other way to do this (the OOP way if you will) would be with a FilterIterator (PHP 5 >= 5.1.0) might be a bit overkill but does the job. Just change the constructor and accept methods to adjust for your data (currently it works for the array you provided)

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top