简体   繁体   English

使用in_array进行数组

[英]Using in_array for array

So, I have the following php: 因此,我有以下php:

<?php 
$user_id = get_current_user_id();   
$user_number= get_user_meta($user_id, 'number', false); 
$numbers= print_r($user_number);    
?>

I get the following: 我得到以下内容:

Array
(
[0] =&gt; Array
    (
        [1] =&gt; 769099
        [2] =&gt; 768785
        [3] =&gt; 769135
        [4] =&gt; 769118
        [5] =&gt; 769136
        [6] =&gt; 769122
        [7] =&gt; 769130
    )

)

Now, I am trying to use in_array to add a condition as following: 现在,我尝试使用in_array添加条件,如下所示:

<?php if (in_array ($number_id, $numbers)){?>

where $number_id is one of the number in the array. 其中$ number_id是数组中的数字之一。

I have two questions: 我有两个问题:

Do I have to use print_r to get the values instead of simply saying Array in order to use in_array ? 我是否必须使用print_r来获取值,而不是简单地说Array才能使用in_array

How do I actually user in_array ? 我实际上如何使用in_array in this case? 在这种情况下?

(For example, using the get_user_meta , I simply get Array . I don't want to use print_r . How do I do this? Thanks!) (例如,使用get_user_meta ,我只是获取Array 。我不想使用print_r 。我该怎么做?谢谢!)

print_r() is normally print your array. print_r()通常会打印您的数组。 Your code Should be: 您的代码应为:

<?php 
$user_id = get_current_user_id();   
$user_number= get_user_meta($user_id, 'number', false);   
?>

If you want to check number_id in your current user number array than your code should be : 如果要检查current user number数组中的number_id ,则代码应为:

if(in_array('769118',$user_number[0])){ // 769118 is $number_id
    echo "Match Found";
}else{
    echo "No Match Found";  
}

You can refer this link : in_array 您可以参考以下链接: in_array

print_r() is only a function to display the values within an array. print_r()只是一个用于显示数组中的值的函数。

In your case the function get_user_meta() retrieve the numbers associated with the user_id and nothing more. 在您的情况下,函数get_user_meta()检索与user_id关联的数字,仅此而已。

And the function in_array() is there to check to the existence of a specific value within an array. 函数in_array()可以检查数组中是否存在特定值。

尝试这个

<?php if (in_array ($number_id, $user_number[0])){?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM