Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

php - Getting warning : implode(): after receiving a var value

I am having the following errors:

Warning : array_map(): Argument #2 should be an array in...

Warning : implode(): Invalid arguments passed in wp-includes/class-wp-query.php on line 1918

On my php I am receiving a var from another page and I do:

$myId = $_POST['varPostId'];
$parts = explode(',', $myId);

And then I need to read that value

query_posts(array(
    'post__in' => $myId
));

But I get the above errors.

if I do:

    'post__in' => $parts
));

I get a blank page.

I tried using implode

$myId = $_POST['varPostId'];
$parts = implode(',', $myId);

And getting the value directly in the query

query_posts(array(
    'post__in' => $_POST['varPostId']
));

$_POST['varPostId'] is a single value like 405

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems that the value you're getting from the POST request is containing just a single post ID which should be an int but is possibly a string. You'll need to do some type and error checking. Something like the following should hopefully work. I see query_posts and post__in, I'm assuming WordPress is at play here?

// Put your ID into a variable and sanitize it
$myId = sanitize_key( $_POST['varPostId'] );

// Force it to an int (in case it's not from sanitize_key)
$myId = (int) $myId;

// Don't explode because it's not appropriate here
// $parts = explode( ',', $myId );

// Add the post id to the arguments as an array
query_posts(
  array(
    'post__in' => array( $myId )
  )
);

To follow up on why explode isn't appropriate here, it's used to convert a string, usually something like this:

oh, hello, world

Into an array with multiple items like the following:

$asdf = array(
  0 => 'oh',
  1 => 'hello',
  2 => 'world'
);

But you it seems that you don't have a comma separated string of post ids, you just have the one so it's best not used here.

As already stated in the comments, explode takes a string and splits it into an array of items. implode does the opposite. It takes an array and condenses it down into a string.

So you could have something such as:

$myArray = array(
  0 => 'hello',
  1 => 'world'
);

// Convert to a string
$myString = implode( ', ', $myArray );

echo $myString; // prints: hello, world

// Convert back to an array
$myString = explode( ', ', $myArray );

var_dump( $myString ); // prints the array above

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...