【问题标题】:PHP in_array vs array created by mysqli fetch_all() // recursive in_array() func needed [duplicate]PHP in_array 与 mysqli fetch_all() 创建的数组 // 需要递归 in_array() func [重复]
【发布时间】:2022-12-04 08:52:45
【问题描述】:

注意:我在另一篇文章中找到了我的问题的答案。这是答案:

PHP string search in multidimensional array


我的原帖: 我在使用 PHP mysqli fetch_all() 函数创建的数组时遇到问题。

通过 mysqli fetch_all() 创建数组后,我检查数组是否包含来自变量的字符串,我使用 in_array() 或 array_search() 结果为假,即使我知道该字符串在数组中的某处。

思考fetch_all() 函数必须创建一个多维数组,in_array() 和 array_search() 不能按照我认为的方式处理。

下面是从 mysqli 创建 $hotlistarray 的代码:

$hotlistsql='select plate from hotlist where notifyPOCUID ='.$id.' ;';
$hotlistlink = set_up_mysql_link ();  //custom function
$tempresult = mysqli_query($hotlistlink, $hotlistsql);
if ($tempresult !== false) {
        $hotlistarray = $tempresult->fetch_all();
} // End if tempresult is false

var_dump($hotlistarray) 显示如下:

array(4) { [0]=> array(1) { [0]=> string(7) "CYS5584" } [1]=> array(1) { [0]=> string(7) "RKV7350" } [2]=> array(1) { [0]=> string(7) "NTV7839" } [3]=> array(1) { [0]=> string(7) "HXS6267" } }

思考问题是我在 $hotlistarray 中有一个数组数组,需要将它们转换成一个仅包含

研究链接:

PHP in_array function doesn't work

PHP in_array function not working with mysqli_fetch_array

答案:递归 in_array 函数! PHP string search in multidimensional array

【问题讨论】:

  • 为什么要复制现有帖子?

标签: php arrays multidimensional-array mysqli


【解决方案1】:

在这篇文章中找到了答案:

PHP string search in multidimensional array

@Paolo 用这段代码回答:

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        // cast $item to string if numeric when doing weak comparison
        if( ! $strict && is_string( $needle ) && ( is_float( $item ) || is_int( $item ) ) ) {
            $item = (string)$item;
        }
        // ----------------------------------------------------------

        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}

谢谢@Paolo!

【讨论】:

    猜你喜欢
    • 2014-07-26
    • 1970-01-01
    • 2011-03-30
    • 2012-10-05
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多