Sajeev C Sajeev C - 5 months ago 25
PHP Question

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!

Answer

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