3

I have an array "$arrItems['items']" in which 5 more arrays(associate array) and each array contain 5 element(f_name,l_name,contact,address,seller_id).
Actually I want to get all those arrays(from "$arrItems['items']") in which element of seller_id is 1 like "seller_id"=>1
Code given below. Guide me how to use foreach loop or else . . .

array(5)
{
[0] =>
array(5)
{
["f_name"] =>
string(3) "abc"
["l_name"] =>
string(3) "xyz"
["contact"] =>
string(5) "12345"
["address"] =>
string(3) "xyz"
["seller_id"] =>
string(1) => "1"
}
[0]=>
array(5) {
    ["f_name"]=>
string(3) "abc"
    ["l_name"]=>
string(3) "xyz"
    ["contact"]=>
string(5) "12345"
    ["address"]=>
string(3) "xyz"
    ["seller_id"]=>
string(1)=>"1"
}
[1]=>
array(5) {
    ["f_name"]=>
string(3) "abc"
    ["l_name"]=>
string(3) "xyz"
    ["contact"]=>
string(5) "12345"
    ["address"]=>
string(3) "xyz"
    ["seller_id"]=>
string(1)=>"5"
}
[2]=>
array(5) {
    ["f_name"]=>
string(3) "abc"
    ["l_name"]=>
string(3) "xyz"
    ["contact"]=>
string(5) "12345"
    ["address"]=>
string(3) "xyz"
    ["seller_id"]=>
string(1)=>"1"
}
[3]=>
array(5) {
    ["f_name"]=>
string(3) "abc"
    ["l_name"]=>
string(3) "xyz"
    ["contact"]=>
string(5) "12345"
    ["address"]=>
string(3) "xyz"
    ["seller_id"]=>
string(1)=>"1"
}
[4]=>
array(5) {
    ["f_name"]=>
string(3) "abc"
    ["l_name"]=>
string(3) "xyz"
    ["contact"]=>
string(5) "12345"
    ["address"]=>
string(3) "xyz"
    ["seller_id"]=>
string(1)=>"3"
}
}
1
  • You should post it to stack exchange.
    – anonymous
    Commented Feb 21, 2019 at 12:41

2 Answers 2

1

Use the array_filter php function.

$filtered = array_filter(
    $arrItems['items'],
    function ($item) {
        return isset($item['seller_id']) && $item['seller_id'] == 1;
    }
);
1
  • I think the answer should provide some more explanation. Commented Feb 21, 2019 at 13:54
0

Fortunatly am giving answer of my own question

$arr = [];
foreach ($arrItems['items'] as $i => $row) {
    if ($row['seller_id'] != 1) {
        // Ignore row if seller_id is not 1
        continue;
    }

    // here you got only elements with seller_id = 1
    // so you can add them to a new array
    $arr[] = $row;
}

// After the loop (foreach) in $row you get only elements with seller_id 1.
// If they must be in $arrItems['items'] use it
$arrItems['items'] = $arr;

echo '<pre>';
print_r($arrItems['items']);
echo '</pre>';

The Output is :

Array
(
    [f_name] => abc
    [l_name] => xyz
    [contact] => 12345
    [address] => xyz
    [seller_id] => 1
)
Array
(
    [f_name] => abc
    [l_name] => xyz
    [contact] => 12345
    [address] => xyz
    [seller_id] => 1
)
Array
(
    [f_name] => abc
    [l_name] => xyz
    [contact] => 12345
    [address] => xyz
    [seller_id] => 1
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.