我需要确定一个数组(针)中的值出现在另一个数组(干草堆)中的每个实例。in_array()
似乎是我最好的选择,并且下面的代码可以正常工作,直到我需要在从db提取的行上使用它为止-它始终附加值,而不是每次调用时都对其进行设置。
尽管我实际上不能unset()
在这种情况下使用,但我惊讶地发现,即使那样似乎也无法解决问题。
更新-返回的示例
我临时更改了db的值,以使$ needles每行仅具有一个值(以便可以对填满屏幕的值进行排序;-))
- 错误的;
- 错误的; 错误的; 真的;
- 错误的; 错误的; 真的; 错误的; 真的;
- 错误的; 错误的; 真的; 错误的; 真的; 错误的; 真的;
- 错误的; 错误的; 真的; 错误的; 真的; 错误的; 真的; 错误的;
这可以正常工作 (我在这里发布了一个功能示例)
$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');
foreach ($needles as $needle) {
if (in_array($needle, $haystack) ) {
$Match = 'True';
}
else {
$Match = 'False';
}
}
这会不断附加值-已编辑以反映我正在使用的代码
$Customer_Categories_Arr = array('Casual','Trendy');
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$Product_Categories_Arr[]=$row["Taste_Category"];
// Use when column contains CSV
// $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));
foreach ($Product_Categories_Arr as $Product_Category_Arr) {
if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){
$Matches_Product_Category = "True";
} else {
$Matches_Product_Category = "False";
}
echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
}
}
}
目前尚不清楚您要做什么。但这也许会有所帮助:
$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
$productCategoryRow = $row[ 'Taste_Category' ];
// If it is not working, try uncommenting the next line
// $productCategories = [];
$productCategories = explode( ',', trim( $productCategoryRow ));
$match = "False";
foreach( $productCategories as $productCategory ){
if( in_array( $productCategory, $customerCategories )){
$match = "True";
}
echo $match . ";";
}
}
}
每次循环时,这都会在屏幕上打印结果。你是这个意思吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句