我有一个数组$ arrItems ['items'],其中还有5个数组(关联数组),每个数组包含5个元素(with the keys: f_name, l_name, contact, address, seller_id
)。
我想获取所有这些数组(从$ arrItems ['items']获取),其中Seller_id的元素为1,例如"seller_id"=>"1,2,3"
或"seller_id"=>"3,2,1"
或"seller_id"=>"4,6,2"
或{{1} }或"seller_id"=>"5,3,4"
数组如下。
"seller_id"=>"2,1,2"
请帮助我,它实际上是在订购表,我只想选择当前卖方id为1的那些数组。例如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,2,3"
}
[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)=>"3,2,1"
}
[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)=>"4,6,2"
}
[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)=>"5,3,4"
}
[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)=>"2,1,2"
}
是登录名。那么所有这些选择的数组都意味着这些数组保存在另一个数组中。
答案 0 :(得分:1)
array_filter
(documentation)和in_array
(documentation):
$sellerId = "1";
$arr = array_filter($arrItems['items'], function($e) use ($sellerId) {
return in_array($sellerId, explode(",", $e["seller_id"]);
});
如果只希望使用这5个选项:
$options = array("1,2,3", "3,2,1", "5,3,4", "4,6,2", "2,1,2");
$arr = array_filter($arrItems['items'], function($e) use ($options ) {
return in_array($e["seller_id"], $options);
});
已编辑:根据您的请求,这是使用foreach
循环的同一代码的版本:
$sellerId = "1";
$seller_order_arr = [];
foreach ($arrItems['items'] as $row) {
if (in_array($sellerId, explode(",", $row["seller_id"])))
$seller_order_arr[] = $row;
}
现在$seller_order_arr
将保留您的过滤数组
答案 1 :(得分:0)
如果我正确看到的话,那么您的seller_id
值是一个由Ids组成的串联字符串。您可以使用array_filter
和自定义回调函数过滤外部数组,如果应该保留该元素,则该函数应返回true
。
$idToLookup = 1;
$filteredItems = array_filter($arrItems['items'], function($element) {
return preg_match('/(^|,)' . $idToLookup . '($|,)/', $element['seller_id']);
]);
或者,如果您不太熟悉正则表达式,请先将数字字符串分解为单个数字,然后使用in_array
:
$idToLookup = 1;
$filteredItems = array_filter($arrItems['items'], function($element) {
$sellerIds = explode(',', $element['seller_id']);
return in_array($idToLookup, $sellerIds);
]);
答案 2 :(得分:-1)
使用array_filter()
$array = array_filter($arrItems['items'], function ($item) {
$ids = explode(',', $item['seller_id']);
return in_array(1, $ids);
});