我有一个数组$categories
,如下所示;
Array
(
[0] => Array
(
[category_id] => 0
)
[1] => Array
(
[category_id] => 3
)
)
我想在foreach中应用一些条件如下;
注意:以下条件不起作用;
foreach ($categories as $key=> $category)
{
if($category['category_id']===0)
{
$categories[$key]['category_name'] = 'NA';
}
else
{
$categories[$key]['category_name'] = 'something';
}
}
所以我的预期结果会变成;
Array
(
[0] => Array
(
[category_id] => 0
[category_name] => NA
)
[1] => Array
(
[category_id] => 3
[category_id] => something
)
)
答案 0 :(得分:2)
在数组中,0
可能是您使用===
运算符检查的字符串,它也会将字符串与其数据类型匹配。
如果需要,您可以使用gettype($value)
检查其数据类型。
对于当前问题,请尝试:
/* Compare value without checking its datatype */
if($category['category_id'] == 0) /* replace === to == */
{
$categories[$key]['category_name'] = 'NA';
}
else
{
$categories[$key]['category_name'] = 'something';
}