开发者

array search not working

开发者 https://www.devze.com 2023-03-19 20:18 出处:网络
i have got the folowing code. $coauthors = get_post_meta( $post_id, \"coAuthors\" ); print_r($coauthors);

i have got the folowing code.

$coauthors = get_post_meta( $post_id, "coAuthors" );

print_r($coauthors);

ok result from print_r is

Array ( [0] => 78 ) Array ( [0] => 78 )

now my user id is 78 so it should return true with the follow code but it doesnt.

$key = array_search( 78, $coauthors );

     if($key) { 

     return true;

     }else{

     echo "no"; 

     }

Why do i always get no where am i going wrong what the best way to do this???

Thanks

Im still getting issues here is my function.

   add_action('is_true','isdAuthorTrue');

    function isdAuthorTrue( $post_id ) { 

        $current_user = wp_get_current_user();
    if ( !($current_user instanceof WP_User) )
    return;

        $current_user = wp_get_current_user();

         $coauthors = get_post_meta( $post_id, "coAuthors" );

         $key = array_search( $current_user->ID, $coauthors );
         $key = 0;
         if($key !== false) {

           return true;

         } else {

             return false;
         }


        }  

and then i am trying to run this in the l开发者_运维问答oop.

if(do_action( 'is_true', $post->ID )){

    echo "yes";

}else{

    echo "no";
}

help???


$key = 0;

That results in false.

You should check for key like this:

if($key !== false) {
    // do sth with it
} else {
    // does not exist
}


Because no entry in $coauthors has the value 78. $coauthors is an array of arrays, and one of the sub-arrays has the value 78 in it.

So you'd need to search all the sub-arrays.

edit: hm, you sure your print_r results in a printout that looks like that? Looks odd...


In this example, the key value will be 0 because that is the index in the array where 78 is a value. Thus says if($key) will fail when $key = 0, even if $key is a valid array index.

To check for validity, what you should be doing is something like the following

if (in_array(78, $coauthors)) {
    $key = array_search(78, $coauthors);
    // do what you want with $key and the $coauthors array
}
0

精彩评论

暂无评论...
验证码 换一张
取 消