【问题标题】:In_array not workingIn_array 不工作
【发布时间】:2014-09-19 09:48:05
【问题描述】:

我有一个数组,我应用了 in_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
    )
}

我正在使用的代码:

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

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

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

它只显示'NO'..请帮助我...

【问题讨论】:

  • 我认为这是因为“对象数组”介于两者之间。可能是因为它不起作用。
  • @Khushboo 如何从数组中删除该对象,有什么方法吗??
  • 你有一个对象数组。遍历它们并检查您的价值是否在其中。
  • 在数组中找不到'285078',因为它在数组中不是。你所拥有的是一组SimpleXMLElement 对象。
  • "... 获取数据而不是将其保存在数组中..." 当你这样做时,不要将 SimpleXMLElement 添加到数组中,而是它所呈现的价值。

标签: php arrays xml simplexml


【解决方案1】:

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

$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';
}

【讨论】:

    【解决方案2】:

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

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

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

    $your_array[] = strval($appended_value);
    

    之后你可以使用in_array

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 将数组转换为数组?嗯
        • 我觉得还是不搜索
        • 不会进行类型转换吗?
        • 是的,将对象转换为数组?
        • 是的,所以他只得到数组而不是对象数组
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多