我有一个从json_decode创建的数组,如下所示,创建了一个对象数组。我有两个问题,一个是功能没有按预期工作,另一个是性能相关的问题。这就是我所拥有的:
{
"info": {
"options": [{
"optionID": 123
},
{
"optionID": 456
},
{
"optionID": 789
}
]
}
}
不幸的是,json_decode
是在其他地方完成的,如果更改,将破坏许多其他代码,因此不能将true
传递给json_decode。
$data = file_get_contents('/datastore.json');
$options = json_decode($data);
var_dump($idpassed);
var_dump($options);
以上产生:
int(123)
array(3) {
[0]=>
object(stdClass)#551 (16) {
["optionID"]=> (int)123
},
[1]=>
object(stdClass)607 (16) {
["optionID"]=> (int)456
},
[2]=>
object(stdClass)#663 (16) {
["optionID"]=> (int)789
}
}
我正在尝试查找"optionID"属性是否存在,具体取决于其他地方设置的值。因此,我正在这样做:
if (array_search($idpassed, array_column($options, 'optionID')) !== FALSE) {
echo "the option exists!";
} else {
echo "the option does not exist!";
}
问题1:如果$idpassed
是456
或789
,则始终返回true,正如我所期望的那样。然而,如果我传入123
,它将失败,可能是因为options
索引的数组是0
,这是false。对于这种方法,!== FALSE
还有哪些其他选项?我尝试过的所有东西(例如===false或===true,都不起作用,因为返回了0
密钥。
作为另一种方法,我只做了一个简单的foreach,它如预期的那样工作:
$exists = false;
foreach ($options as $option) {
if ($option->optionID === $idpassed) {
$exists = true;
break;
}
}
print_r($exists)
对于123
、456
和789
,此方法返回true,对于我不期望的任何内容,此方法都返回false。问题2:那么,哪种方法对性能更好,为什么?我认为array_column方法应该更快,因为它是一个直接的C实现,但不能100%确定。
非常感谢!
类型为字符串,因此使用:$idpassed='123';