1

My array like this :

$myArray = array(
    array(
        'uid' => '100',
        'name' => 'Michael',
        'pic_square' => 'urs121'
    ),
    array(
        'uid' => '200',
        'name' => 'machavent',
        'pic_square' => 'urs222'
    ),
    array(
        'uid' => '300',
        'name' => 'Ayem',
        'pic_square' => 'urs333'
    ),
    array(
        'uid' => '400',
        'name' => 'Bucin',
        'pic_square' => 'urs444'
    ),
    array(
        'uid' => '500',
        'name' => 'Bangcad',
        'pic_square' => 'urs555'
    )
);

this my function :

function filterElement($array, $key, $value){
    foreach($array as $subKey => $subArray){
        if($subArray[$key] != $value){
            unset($array[$subKey]);
        }
    }
    return $array;
}
                        

this working fine if I just need get data from uid=100

$mydata = '100';
$array = filterElement($myArray, "uid", $mydata);

my results

my results

But how if I want to get data from uid = [100,300] ?

I'm trying to call like this

$mydata = ['100','300'];
$array = filterElement($myArray, "uid", $mydata);

and change my function to

function filterElement($array, $key, $value){
    foreach($array as $subKey => $subArray){
        for($i=0;$i<count($value);$i++){
            if($subArray[$key] != $value[$i]){
                unset($array[$subKey]);
            }
        }
    }
    return $array;
}

and the results is

array(0) {
}

so my problem is how to filter data using multi value from multi dimensional array.

1 Answer 1

2

Use array_filter function:

function filterElement($array, $key, $value){
    if (!is_array($value)) $value = [$value];
    return array_filter($array, function($item) use ($key, $value){
        return in_array($item[$key], $value);
    });
}

// Usage:
$array = filterElement($myArray, "uid", '100');
$array = filterElement($myArray, "uid", ['100', '300']);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.