简体   繁体   中英

PHP- in_array() expects parameter 2 to be array

I have two arrays - one single and other multi-dimensional .

$abc='["first","second","third","fourth"]';

$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';

$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);


echo '<pre>';
print_r($jkl);
echo '</pre>';

echo '<pre>';
print_r($ghi);

echo '</pre>';

And this is what it looks like:

Array
(
    [0] => first
    [1] => second
    [2] => third
    [3] => fourth
)

Array
(
    [0] => Array
        (
            [post_id] => 1
            [postid] => 42
            [tags] => Array
                (
                    [0] => eminem
                    [1] => baby
                    [2] => jordan
                )

        )

    [1] => Array
        (
            [post_id] => 3
            [postid] => 38
            [tags] => Array
                (
                    [0] => abc
                    [1] => def
                    [2] => jordan
                )

        )

    [2] => Array
        (
            [post_id] => 4
            [postid] => 40
            [tags] => Array
                (
                    [0] => eminem
                    [1] => baby
                    [2] => first
                    [3] => second
                    [4] => fourth
                )

        )

)

What I am trying to do is search for the elements of single-dimensional array inside the sub-array tags present in the multi-dimensional array.

This is my code:

$users = array_unique($jkl);
$array = [];
$i=0;   

foreach($users as $user) 
{

    if (in_array($user, $ghi[$i]['tags'])) 
    {
        $newdata =  array (
            'postId' => $ghi[$i]['postid'],
            'tag' => $user
         );
        array_push($array, $newdata);
    }
    $i++;
}

But I get the error mentioned as the question title. What could be the possible reason? Thanks!

Your both array has different numbers of elements. first array has four elements while second array has three elements. that's why you are getting problem.

You should check variable is set and must be an array. Use !empty() and is_array()

foreach($users as $k=>$user){
  if(!empty($ghi[$k]['tags']) && is_array($ghi[$k]['tags'])) { // check this condition here
    if (in_array($user, $ghi[$k]['tags'])){
        $newdata =  array (
            'postId' => $ghi[$k]['postid'],
            'tag' => $user
         );
        array_push($array, $newdata);
    }
  }  
}

Note :- I have used array key as $k instead of $i

You have to iterate through multi-dimensional array and do what you want:-

<?php

$abc='["first","second","third","fourth"]';

$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';

$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);

$users = array_unique($jkl);
$array = []; // empty array
foreach($ghi as $gh)  // iterate through multi-dimensional array not single one
{
for($i=0;$i<count($users);$i++){ // a for loop to iterate through single-dimensional completly
    if (in_array($users[$i],$gh['tags']))  // if single dimensional array value exist in multi-dimensional tags array
    {
        $newdata =  array (
            'postId' => $gh['postid'],
            'tag' => $users[$i]
         );
        array_push($array, $newdata); // push the data
    }
   }
}
echo "<pre/>";print_r($array); // print newly created array
?>

Output:- https://eval.in/602523

Note:- Try to put variable name in such a way that they don't produce ambiguity.Thanks

This is because length of your 2 arrays are different, use isset() to remove error:

as 3rd index of your $ghi array does not exist, and its trying to fetch $ghi[3]['tags'] - that's why error is occurring

Try:

foreach($users as $user) 
{
    if(isset($ghi[$i]['tags'])) { // just add this condition here
      if (in_array($user, $ghi[$i]['tags'])) 
      {
          $newdata =  array (
              'postId' => $ghi[$i]['postid'],
              'tag' => $user
           );
          array_push($array, $newdata);
      }
    }
    $i++;
}

It depends on what you are searching for. If you want to examine ALL of the $users against ALL of the $ghi array then you need to loop over both each time.

foreach($users as $user)
{
  for ($i = 0; $i < count($ghi); $i++) {
    if (in_array($user, $ghi[$i]['tags']))
    {
        $newdata =  array (
            'postId' => $ghi[$i]['postid'],
            'tag' => $user
         );
        array_push($array, $newdata);
    }
  }
} 

This will result in the $newdata consisting of the following

array(2) { ["postId"]=> string(2) "40" ["tag"]=> string(6) "fourth" } 

But if you only want to examine the each array against the other once. Then you need to check to make sure you're not going out of bounds.

$ghi only has 3 elements in it. there are 4 elements in $users.

So you can either loop through the smaller array in your foreach - switch $users -> $ghi or check inside the foreach loop that $ghi has a valid element at whatever $i is.

D.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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