我有这样的变量列表:
$item[1]['Value']
$item[2]['Value']
...
$item[50]['Value']
其中一些是null
.
如何检查其中是否至少有一个不为空,在这种情况下,将该变量(无论是第一个情况还是最后一个情况(定义为新变量?
附言$var[number]['foo']
格式的名称是什么?它是一个数组吗?
使用empty()
函数的简单测试
if(!empty($item[$i]['value'])
{
echo "exists";
}else{
echo "is not set";
}
如果要影响新值(如果新值不存在或未定义(,可以使用null coalescing operator
$item[$i]['value'] = $item[$i]['value'] ?? $newvalue;
检查其中至少一个不为空
<?php
$atleast=0;//all are empty
for($i=0;$i<count($item);$i++)
{
if(!empty($item[$i]['value']))
$atleast=1;//one is empty;
}
if($atleast==1)
echo "there is more than one element which are not empty";
else
echo "all are emtpy";
?>
将最后找到的已用元素设置为 newVariable
。
for($i = 0; $i < sizeOf($item); i ++)
{
if(isset($item[$i]['Value']))
{
$newVariable = $item[$i]['Variable'];
}
}
如果要使用内部键作为变量名,则可以检查是否可以创建它,如果是,则可以创建它:
function any($array) {
foreach ($array as $key => $item) {
if ($item) return $key;
}
return false;
}
$variableName = any($var);
if ($variableName !== false) {
{$variableName} = "yourvalue";
} else {
//We ran out of variable names
}
附言$var[number]['foo']
的格式是一个外部带有数字键的数组,内部带有字符串键的数组。
你可以像这样array_filter()
和使用empty()
:
// example data
$items = [
['Value' => null],
['Value' => 2],
['Value' => null],
];
// remove elements with 'Value' = null
$filtered = array_filter($items, function($a) { return !is_null($a['Value']); }) ;
$element = null;
// If there is some values inside $filtered,
if (!empty($filtered)) {
// get the first element
$element = reset($filtered) ;
// get its value
$element = $element['Value'];
}
if ($element)
echo $element ;
将输出:
2
-
array_filter()
返回一个具有非空值的数组(使用 use 函数(。 -
empty()
检查数组是否为空。 -
reset()
获取数组中的第一个元素。
如果要检查数组中所有项目的所有值,则可以使用foreach。
示例:
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
echo "$key It's not empty n";
} else {
echo "$key It's empty n";
}
}
结果:
1 It's not empty
2 It's not empty
3 It's empty
4 It's empty
您还可以看到空函数将 NULL 视为空。
-----编辑-----
我忘了添加方法来检测是否至少有一个项目为空,您可以使用:
例
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
$item_result = false;
} else {
$item_result = true;
}
}
if ($item_result) {
echo "At least one item is empty";
} else {
echo "All items have data";
}
结果:
At least one item is empty
<?php
$data =
[
1 => ['foo' => ''],
2 => ['bar' => 'big'],
10 => ['foo' => 'fat']
];
$some_foo = function ($data) {
foreach($data as $k => $v)
if(!empty($v['foo'])) return true;
return false;
};
var_dump($some_foo($data));
$data[10]['foo'] = null;
var_dump($some_foo($data));
输出:
bool(true)
bool(false)
或者,您可以过滤计算结果为 false 的 foo 值:
$some_foo = (bool) array_filter(array_column($data, 'foo'));