PHP in_array不能使用当前的数组结构

时间:2015-05-27 10:16:45

标签: php sql arrays function

我正在使用自定义方法将查询作为数组返回。

这用于检查发布的折扣代码是否在数据库中。

数组结束为例:

Array
(
[0] => stdClass Object
    (
        [code] => SS2015
    )

[1] => stdClass Object
    (
        [code] => SS2016
    )

)

所以,当我想要做的时候:

if ( ! in_array($discount_code, $valid_codes)) {

}

它不起作用。有没有办法我仍然可以使用该函数查询我正在使用的数组并检查它是否在数组中?

没有问题,我可以制作一个简单的代码数组,但只是想保持一致。

4 个答案:

答案 0 :(得分:1)

阅读json_encode(序列化数据到json)和json_decode(如果secondary param为true,则从序列化json返回关联数组)。此外,array_column按字段名称获取值。所以我们在1维数组中有数组值,然后用in_array检查。

void

答案 1 :(得分:0)

使用array_filter()标识属性code等于$discount_code的对象:

$in_array = array_filter(
    $valid_codes,
    function ($item) use ($discount_code) {
        return $item->code == $discount_code;
    }
);

if (! count($in_array)) {
    // $discount_code is not in $valid_codes
}

如果您需要在不同的文件中多次执行相同的检查,您可以将上面的代码段转换为函数:

function code_in_array($code, array $array)
{
    return count(
        array_filter(
            $array,
            function ($item) use ($code) {
                return $item->code == $code;
            }
        )
    ) != 0;
}


if (! code_in_array($discount_code, $valid_codes)) {
    // ...
}

答案 2 :(得分:0)

试试这个

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

return false;
}

然后

echo in_array_r("SS2015", $array) ? 'found' : 'not found';

答案 3 :(得分:0)

为什么不把它作为一项学校任务来解决 - 快速而简单:

for($i = 0; $i < count($valid_codes); $i++) if ($valid_codes[$]->code == $discount_code) break;
if ( ! ($i < count($valid_codes))) {  // not in array
}