Getting warning : implode(): after receiving a var

2019-09-21 01:04发布

问题:

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

回答1:

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


标签: php wordpress