php 数组赋值为空内存,php - 检查PHP数组是否为空? - 堆栈内存溢出

编辑:

您的问题已更新两次。 如果其中一个值未填充,您可能想将$bank视为“空” –我的原始答案(以下)仅在所有值均与函数匹配时才返回true 。 我们需要容纳的是一个稍微不同的函数array_some 。

function array_some(callable $f, array $xs) {

foreach (array_values($xs) as $x)

if (call_user_func($f, $x))

return true;

return false;

}

$input = [

[

'bank_name' => [],

'bank_code' => null,

'branch' => null,

'account_number' => null,

'accout_type' => null

],

[

'bank_name' => ['foobar'],

'bank_code' => 123,

'branch' => null,

'account_number' => null,

'accout_type' => null

],

[

'bank_name' => 'Bank Name',

'bank_code' => 7083,

'branch' => 'Branch Name',

'account_number' => '234234324242',

'accout_type' => 'NRFC'

]

];

function is_empty($x) { return empty($x); }

foreach ($input as $bank) {

$proceed = array_some('is_empty', $bank);

echo 'proceed:', json_encode($proceed), PHP_EOL;

}

// proceed:true

// proceed:true

// proceed:false

在第一个示例中, 某些字段为空,因此$proceed将为true

在第二个示例中, 某些字段为空,因此$proceed将为true

在第三个示例中, 所有字段均为非空 ,因此$proceed将为false

原始答案:

您正在寻找的是一个array_every函数。 让我们从一个简单的例子开始:

function array_every(callable $f, array $xs) {

foreach (array_values($xs) as $x)

if (!call_user_func($f, $x))

return false;

return true;

}

function even($x) { return $x % 2 === 0; }

echo "even:", json_encode(array_every('even', [1,2,3])), PHP_EOL; // false

echo "even:", json_encode(array_every('even', [2,4,6])), PHP_EOL; // true

在第一示例中, 1 , 2 ,和3 不都是 even ,所以输出是假的 。

在第二示例中, 2 , 4 ,和6 都是 even ,所以输出是真实的 。

现在用您的数据来看一下

function array_every(callable $f, array $xs) {

foreach (array_values($xs) as $x)

if (!call_user_func($f, $x))

return false;

return true;

}

$input = [

[

'bank_name' => [],

'bank_code' => null,

'branch' => null,

'account_number' => null,

'accout_type' => null

],

[

'bank_name' => ['foobar'],

'bank_code' => 123,

'branch' => null,

'account_number' => null,

'accout_type' => null

]

];

function is_empty($x) { return empty($x); }

foreach ($input as $bank) {

$proceed = array_every('is_empty', $bank);

echo 'proceed:', json_encode($proceed), PHP_EOL;

}

// proceed:true

// proceed:false

在第一个示例数据中, 所有数组值均为empty ,因此$proceed将为true 。

在第二个示例中, 某些值是(非empty ),因此$proceed将为false 。

注意:因为empty 是语言构造而不是函数 ,所以不能使用变量函数来调用它。 –这就是为什么我定义了一个可重用的is_empty函数而不是使用array_every('empty', ...) -这将不起作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值