比较php中的多维和一维数组 [英] Comparing Multi and single dimensional arrays in php
问题描述
我是刚接触php的新手.我想从数组中获取不同维度的内容
I am new to php just playing with some array. I Want to get following things from the array which are of different dimensional
以下是多维数组
$a = array(
array(
'productsid' => 90,
'CouponID' => 50
),
array(
'productsid' => 80,
'CouponID' => 95
),
array(
'productsid' => 80,
'CouponID' => 95
));
以下是一维数组:
$b = array(80,90,95);
我只想将数组的productid索引与一维数组进行比较,并希望获取与其相等的数据.
I want to compare only the productsid index of the array with the single dimensional array and wants to fetch the data which is equal to it.
我尝试了以下循环进行打印,但是它仅给出productid的值,但是我需要完整的数组.但是只能通过将Productid与第二个数组进行比较.
I Have tried the following loop to print but it only gives the values of the productsid only but I want that full array. But only by comparing the Productid with the second array.
for ($i = 0; $i < 3; $i++) {
foreach ($a[$i] as $key => $value) {
foreach ($b as $c) {
if ($value == $c) {
echo $value .'<br>';
}
}
} }
推荐答案
看起来您正在寻找 in_array()
:
Looks like you're looking for in_array()
:
$result = array();
foreach($a as $item)
if(in_array($item['productsid'], $b))
$result []= $item;
或者,以一种更简洁(但不太易懂的IMO)的方式:
or, in a more concise (but less readable IMO) way:
$result = array_filter($a, function($item) use($b) {
return in_array($item['productsid'], $b);
});
对于您的测试数据来说无关紧要,但是如果您的数组很大和/或此循环将运行多次,则可以通过将查找数组转换为哈希表并使用 O(1)
键查找,而不是线性数组搜索:
For your test data it's doesn't matter much, but if your arrays are big and/or this loop is going to run many times, you can achieve better performance by converting the lookup array into a hash table and using O(1)
key lookup instead of linear array search:
$bs = array_flip($b);
$result = array_filter($a, function($item) use($bs) {
return isset($bs[$item['productsid']]);
});
这篇关于比较php中的多维和一维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!