php In_array 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25931054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:03:37  来源:igfitidea点击:

In_array not working

phparraysxmlsimplexml

提问by DeDevelopers

I have an array, I applied in_array function to find a specific number in that array, but it's showing no result, the data is inside the array but no response..:(

我有一个数组,我应用 in_array 函数在该数组中查找特定数字,但没有显示结果,数据在数组内但没有响应..:(

Array:

大批:

 Array
(
[0] => SimpleXMLElement Object
    (
        [0] => 572140
    )

[1] => SimpleXMLElement Object
    (
        [0] => 533167
    )

[2] => SimpleXMLElement Object
    (
        [0] => 572070
    )

[3] => SimpleXMLElement Object
    (
        [0] => 572383
    )

[4] => SimpleXMLElement Object
    (
        [0] => 285078
    )

[5] => SimpleXMLElement Object
    (
        [0] => 430634
    )
}

CODE I AM USING:

我正在使用的代码:

 if(in_array('285078',$arr))
    {
        echo 'yes';
    }
    else
    {
       echo "No";
    }

This is the array I am creating from the xml file..

这是我从 xml 文件创建的数组。

 $arr = array();
 foreach($xmlInjury as $data)
 {
  array_push($arr,$data->player_id);
 }

It's only showing 'NO'.. please help me on this...

它只显示“不”……请帮我解决这个问题……

回答by Kevin

You need to cast them all first, then search. Like this:

您需要先将它们全部投射,然后进行搜索。像这样:

$new_arr = array_map(function($piece){
    return (string) $piece;
}, $arr);

// then use in array
if(in_array('285078', $new_arr)) {
    echo 'exists';
} else {
    echo 'does not exists';
}

回答by u_mulder

First, your array is not array of strings, it's array of objects. If you can't change the structure of array try this:

首先,您的数组不是字符串数组,而是对象数组。如果你不能改变数组的结构试试这个:

foreach ($your_array as $item) {
    if (strval($item) == '25478') {
        echo 'found!';
        break;
    }
}

If you can change your array, add items to it like this:

如果您可以更改数组,请像这样向其中添加项目:

$your_array[] = strval($appended_value);

After that you can use in_array.

之后,您可以使用in_array.

回答by Luká? Rutar

in_array is not recursive, it searches only on first level. and first level member of you array are SimpleXMLElement Objects, not an numbers.

in_array 不是递归的,它只在第一级搜索。数组的第一级成员是 SimpleXMLElement 对象,而不是数字。

回答by Khushboo

Try with typecasting your array :-

尝试对数组进行类型转换:-

$array =  (array) $yourarray;
if(in_array('285078',$arr))
    {
        echo 'yes';
    }
    else
    {
       echo "No";
    }