PHP- in_array() expects parameter 2 to be array - php

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!

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

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

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.

Related

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

Combine two arrays into a single array based on a common column value

I am trying to combine two arrays while respecting their shared value.
$array1 = array(
array("id" => "1","name"=>"John"),
array("id" => "2","name"=>"Peter"),
array("id" => "3","name"=>"Tom"),
array("id" => "12","name"=>"Astro")
);
$array2 = array(
array("id" => "1","second_name"=>"Lim"),
array("id" => "2","second_name"=>"Parker"),
array("id" => "3","second_name"=>"PHP")
);
My expected output:
$result = array(
array("id" => "1","name"=>"John","second_name"=>"Lim"),
array("id" => "2","name"=>"Peter","second_name"=>"Parker"),
array("id" => "3","name"=>"Tom","second_name"=>"PHP"),
array("id" => "12","name"=>"Astro")
);
I have made a try by
$arraycomb = array_unique(array_merge($array1,$array2), SORT_REGULAR);
My output is:
Array
(
[0] => Array
(
[id] => 1
[name] => John
)
[1] => Array
(
[id] => 2
[name] => Peter
)
[2] => Array
(
[id] => 3
[name] => Tom
)
[3] => Array
(
[id] => 12
[name] => Astro
)
[4] => Array
(
[id] => 1
[second_name] => Lim
)
[5] => Array
(
[id] => 2
[second_name] => Parker
)
[6] => Array
(
[id] => 3
[second_name] => PHP
)
)
How can I combine the key value inside same array? or how can I bring the expected output?
Note: I am trying for value instead of key ref: PHP Array Merge two Arrays on same key
Alternatively, you could use a foreach in this case then merge them if they share the same id key
With using reference &
foreach($array1 as &$value1) {
foreach ($array2 as $value2) {
if($value1['id'] == $value2['id']) {
$value1 = array_merge($value1, $value2);
}
}
}
echo '<pre>';
print_r($array1);
You can use array_map() for this. Try this -
function modifyArray($a, $b)
{
if (!empty($a) && !empty($b)) {
return array_merge($a, $b);
} else if (!empty($a) && empty($b)) {
return $a;
} else if (empty($a) && !empty($b)) {
return $b;
}
}
$new = array_map("modifyArray", $array1, $array2);
var_dump($new);
It will generate the new array will all the values in both arrays.if the first array's element is empty then the second array will be merged and vice-versa.
Assign temporary first level keys to your first array to aid in identifying rows. Then loop the second array and append the desired column value to the appropriate group. Re-index the array after looping with array_values().
Code: (Demo)
$result = array_column($array1, null, 'id');
foreach ($array2 as $row) {
$result[$row['id']]['second_name'] = $row['second_name'];
}
var_export(array_values($result));
This is a more direct approach than brute force scanning arrays with nested loops.
If all ids in the second array exist in the first array, then the following simpler line can be written inside the body of the foreach().
$result[$row['id']] += $row;

PHP: array_splice() not giving me correct output

I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}

Creating Associative Array in PHP

I have a multidimensional array.
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
The first item in each array is application number and the rest in each array are the publication numbers. I get the first item(application number) and the last item of each array(latest publication number) like this
$index = count(array_keys($shop));
for($i=0;$i<$index;$i++){
$appln_nr = $shop[$i][0];
echo $appln_nr;
$publn_nr_index = count(array_keys($shop[$i]))-1;
$publn_nr = $shop[$i][$publn_nr_index];
echo $publn_nr;
}
Now I have application number and publication number for each inner array.
I want to create an associative array from the application numbers and publication numbers.
where the key should be the application number and its value is the publication number.
Thanks
EDIT
What I am getting from $shop array
Array
(
[0] => Array
(
[0] => appn1
[1] => pub1
[2] => pub2
[3] => pub3
)
[1] => Array
(
[0] => appn2
[1] => pub1
)
[2] => Array
(
[0] => appn3
[1] => pub1
[2] => pub2
)
)
And this is what I need in my associative array
Array(
"appn1" => "pub3"
"appn2" => "pub1"
"appn3" => "pub2"
)
Finally i understood what you wanted, after your edit XD:
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
$shopNew = array();
foreach($shop as $value){
$shopNew[$value[0]] = end($value);
}
// now if you want you can replace $shop and unset $shopNew
$shop = $shopNew;
unset($shopNew);
print_r($shop);
the output is this:
Array (
[appn1] => pub3
[appn2] => pub1
[appn3] => pub2
)
You can try
$shop = array(
array("appn1","pub1","pub2","pub3"),
array("appn2","pub1"),
array("appn3","pub1","pub2")
);
$final = array();
array_map(function ($var) use(&$final) {$final[reset($var)] = end($var);}, $shop);
var_dump($final);
Output
array
'appn1' => string 'pub3' (length=4)
'appn2' => string 'pub1' (length=4)
'appn3' => string 'pub2' (length=4)
You can easily convert your array into a new format by using the first element as key (see reset) and the last element (see end) as value:
foreach($shop as $fl) {
$v[reset($fl)] = end($fl);
}
Result is in $v then.
If you want to transform the array you need to delete each element as well:
foreach($shop as $v => $fl) {
$shop[reset($fl)] = end($fl);
unset($shop[$v]);
}
Result is in $shop then. Unset takes care of removing from the array.
Output in both cases is:
array(3) {
'appn1' =>
string(4) "pub3"
'appn2' =>
string(4) "pub1"
'appn3' =>
string(4) "pub2"
}
try this:
foreach($shop as $k => $v) {
$new_arr[$v[0]] = end($v);
}
It should give you this result,
$new_arr = array(
"appn1" => "pub3",
"appn2" => "pub1",
"appn3" => "pub2"-
);
You can also create like this,
$arrField = [];
$arrField['id'] = '0001';
$arrField["first_name"] ='Demo Test';
print_r($arrField);
print_r($arrField) display output like this.
Array ( [id] => 0001 [first_name] => Demo Test )

Checking if array value exists in a PHP multidimensional array

I have the following multidimensional array:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
I'm currently using a foreach loop to extract the values from the array:
foreach ($result as $key => $sub)
{
...
}
But I was wondering how do I see whether a value within the array already exists.
So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?
So after the loop has finished the array will look like this:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
What about looping over your array, checking for each item if it's id is the one you're looking for ?
$found = false;
foreach ($your_array as $key => $data) {
if ($data['id'] == $the_id_youre_lloking_for) {
// The item has been found => add the new points to the existing ones
$data['points'] += $the_number_of_points;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
// The id you were looking for has not been found,
// which means the corresponding item is not already present in your array
// => Add a new item to the array
}
you can first store the array with index equal to the id.
for example :
$arr =Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
//So now you can check the array $new for if the key exists already
if(array_key_exists(1, $new)){
$new[1]['points'] = 32;
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample
$arr = array(
0 =>array(
"id"=> 1,
"name"=> "Bangladesh",
"action"=> "27"
),
1 =>array(
"id"=> 2,
"name"=> "Entertainment",
"action"=> "34"
)
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
if(array_key_exists(1, $new)){
echo $new[1]['id'];
}
else {
echo "aaa";
}
//print_r($new);

Categories