Array PHP, Check if exist multiple elements to another array - php

I have a question about this:
I have two array, one is static, and one can be updated by the user...
I would like to check for every id from the static array if exist the id to the other array, and if exsist, do something, if doesn't exist (when finish to check) pass to other ID etc...
now, the arrays are these:
user array (the user unlock 2 achievement):
Array (
[0] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 644081262362202
[title] => Achievement 2
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement2.html
)
)
[id] => 104693166566570
)
[1] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 968802826528055
[title] => Achievement 1
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement1.html
)
)
[id] => 104023386633548
)
)
the static Array (have 6 achievement saved):
Array (
[0] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement2
[title] => Achievement 2
[id] => 644081262362202
)
[1] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement3
[title] => Achievement 3
[id] => 912599152147444
)
[2] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement5
[title] => Achievement 5
[id] => 913757345379232
)
[3] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement6
[title] => Achievement 6
[id] => 921989084564878
)
[4] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement1
[title] => Achievement 1
[id] => 968802826528055
)
[5] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement4
[title] => Achievement 4
[id] => 1149671038394021
)
)
now, I use this script to echo the final output like the picture (results is the static array):
if (empty($results)) {
//echo 'noAchievement for the app';
} else {
foreach ($results as $result) {
$totalAchievementsApp .= ' [["' . "0" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";
}
}
now, How I can do to check inside the this script? I know I have to add another if inside the else to check if the ID is = to other ID, but I don't know how, I'm a little bit confused... I would like to check if the id of the static array exist in the other array, and if exsist, do this:
**$totalAchievementsApp .= ' [["' . "1" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";**
Thank you very much :)

If I understand correctly, you want to indicate for each entry in the static array whether its ID exists in the user array.
You can use array_column to generate an array of all IDs in the user array. Then use in_array to check if each static ID exists in that array. Set a value to 1 if its found and 0 if its not found.
For the sake of example, I've generated a new final output array. But you could just add the "found" value to each entry of the the static array.
<?php
$static=array(
array('point'=>50,'title'=>'TITLE 1','id'=>54632),
array('point'=>50,'title'=>'TITLE 2','id'=>54344),
array('point'=>50,'title'=>'TITLE 3','id'=>34225),
array('point'=>50,'title'=>'TITLE 4','id'=>2323245),
array('point'=>50,'title'=>'TITLE 5','id'=>23872445),
);
$user=array(
array('id'=>2323245,'title'=>'TITLE 1','point'=>50),
array('id'=>54344,'title'=>'TITLE 2','point'=>50),
array('id'=>34225,'title'=>'TITLE 3','point'=>50)
);
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],array_column($user,'id'))?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'point'=>$entry['point']
);
}
echo"<pre>".print_r($final,true)."</pre>";
With your data, the output is:
Array
(
[0] => Array
(
[found] => 0
[id] => 54632
[title] => TITLE 1
[point] => 50
)
[1] => Array
(
[found] => 1
[id] => 54344
[title] => TITLE 2
[point] => 50
)
[2] => Array
(
[found] => 1
[id] => 34225
[title] => TITLE 3
[point] => 50
)
[3] => Array
(
[found] => 1
[id] => 2323245
[title] => TITLE 4
[point] => 50
)
[4] => Array
(
[found] => 0
[id] => 23872445
[title] => TITLE 5
[point] => 50
)
)
EDIT
Given the more complex structure of your actual arrays, I nested several array_column functions to access the deeper "data > achievement > id" keys in your user array:
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
See the example below:
// initialize the "static" and "user" arrays
$static=array (
0 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement2',
'title' => 'Achievement 2',
'id' => 644081262362202
),
1 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement3',
'title' => 'Achievement 3',
'id' => 912599152147444
),
2 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement5',
'title' => 'Achievement 5',
'id' => 913757345379232
),
3 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement6',
'title' => 'Achievement 6',
'id' => 921989084564878
),
4 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement1',
'title' => 'Achievement 1',
'id' => 968802826528055
),
5 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement4',
'title' => 'Achievement 4',
'id' => 1149671038394021
)
);
$user=array(
0=>array(
'data' => array(
'importance' => 0,
'achievement' => array (
'id' => 644081262362202,
'title' => 'Achievement 2',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement2.html'
)
),
'id' => 104693166566570
),
1 => array (
'data' => array (
'importance' => 0,
'achievement' => array (
'id' => 968802826528055,
'title' => 'Achievement 1',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement1.html'
)
),
'id' => 104023386633548
)
);
// build array of user achievement IDs
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
// generate final array, with "found" values
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],$user_achvmts)?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'description'=>$entry['description'],
'points'=>$entry['data']['points']
);
}
echo"<pre>".print_r($final,true)."</pre>";
The result is:
Array
(
[0] => Array
(
[found] => 1
[id] => 644081262362202
[title] => Achievement 2
[description] => you unlock the achievement2
[points] => 50
)
[1] => Array
(
[found] => 0
[id] => 912599152147444
[title] => Achievement 3
[description] => you unlock the achievement3
[points] => 50
)
[2] => Array
(
[found] => 0
[id] => 913757345379232
[title] => Achievement 5
[description] => you unlock the achievement5
[points] => 50
)
[3] => Array
(
[found] => 0
[id] => 921989084564878
[title] => Achievement 6
[description] => you unlock the achievement6
[points] => 50
)
[4] => Array
(
[found] => 1
[id] => 968802826528055
[title] => Achievement 1
[description] => you unlock the achievement1
[points] => 50
)
[5] => Array
(
[found] => 0
[id] => 1149671038394021
[title] => Achievement 4
[description] => you unlock the achievement4
[points] => 50
)
)
Note that array_column is only available in PHP >= 5.5.0. For older versions, see the Recommended userland implementation for PHP lower than 5.5.
As an alternative to array_column, you could use array_map to build an array of the user IDs:
$user_achvmts = array_map( function($v) {return $v['data']['achievement']['id'];}, $user);
Or even just iterate through the user array:
$user_achvmts=[];
foreach ($user as $v) { $user_achvmts[]=$v['data']['achievement']['id']; }

Related

Merging PHP array adding key

Ok, this question was probably asked many times here. Tried searching for a way that works but I dont find the correct term to search it.
I have following 2 array
Array 1
Array
(
[1] => Array
(
[data] => DFF022
)
[2] => Array
(
[data] => DFF026
)
)
Array 2
Array
(
[0] => Array
(
[number] => INC0000002
[ia] =>
[description] => Printer not working
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
)
[1] => Array
(
[number] => INC0000003
[ia] =>
[description] => Monitor broke down
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
)
)
Now the number of item inside the array is always will be same. If array 1 got 10 items, then array 2 will have 10 items as well.
I'm looking a way to merge the array to something like this
Array
(
[0] => Array
(
[number] => INC1879727
[ia] =>
[description] => Unable to replay CME NS message
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
[data] => DFF022
)
[1] => Array
(
[number] => INC1884171
[ia] =>
[description] => mw_uat - UAT00MSV_LNP6_01_pga_aggregate_limit
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
[data] => DFF026
)
)
Any idea on how to accomplish this?
Using array merge or combine just combines the array and I have double the items I wanted.
You can run a foreach() to inject the data. To directly modify array elements of $arr2 within the loop we precede $value with &, so the value is assigned by reference:
<?php
$arr1 = [
['data' => 'DFF022',],
['data' => 'DFF026',],
];
$arr2 = [
[
'number' => 'INC0000002',
'ia' => '',
'description' => 'Printer not working',
'state' => 'Monitoring - Waiting for Client',
'updated' => '12/30/2020 19.09.01',
'opened' => '12/24/2020 20.35.36',
],
[
'number' => 'INC0000003',
'ia' => '',
'description' => 'Monitor broke down',
'state' => 'Pending - Awaiting Change Approval/Implementation',
'updated' => '12/29/2020 23.57.06',
'opened' => '12/29/2020 08.21.38',
],
];
foreach($arr2 as $key => &$value) {
$value['data'] = $arr1[$key]['data'];
}
Output (print_r($arr2)):
Array
(
[0] => Array
(
[number] => INC0000002
[ia] =>
[description] => Printer not working
[state] => Monitoring - Waiting for Client
[updated] => 12/30/2020 19.09.01
[opened] => 12/24/2020 20.35.36
[data] => DFF022
)
[1] => Array
(
[number] => INC0000003
[ia] =>
[description] => Monitor broke down
[state] => Pending - Awaiting Change Approval/Implementation
[updated] => 12/29/2020 23.57.06
[opened] => 12/29/2020 08.21.38
[data] => DFF026
)
)
working demo

Merge duplicate keys in multi-dimensional array

I have a script that loops through a bunch of data collected from database tables. I've read other similar posts on StackOverflow about merging duplicate array keys, but none of them seem to work for me. Using the code below, I'm building all of the compiled data into an array:
$sql = 'SELECT * FROM '.$qstTable.' WHERE '.$type.'_qst_id = '.$answer['answer_qst'];
$result = $db->sql_query($sql);
$q = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$sql = 'SELECT * FROM '.$catTable.' WHERE '.$type.'_cat_clean = "'.$q[$type.'_qst_cat'].'"';
$result = $db->sql_query($sql);
$cat = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$daField = $cat[$type.'_cat_name'];
if(count($allQsts)){
if(array_key_exists($daField, $allQsts)){
$daData = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
array_push($allQsts[$daField], $daData);
}else{
$allQsts[$cat[$type.'_cat_name']][] = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
}
}else{
$allQsts[$cat[$type.'_cat_name']][] = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
}
And this is how my array turns out looking when it's all processed:
Array (
[Ancestry] => Array (
[0] => Array (
[question] => Array (
[id] => 1
[qst] => Has your family always lived in this country? Where did your family come from? How did they come here?
)
[answer] => Array (
[id] => 28
[type] => text
[content] => idk
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 158
[qst] => Who were your best friends in high school? Were they the same ones from grade school? Do you still keep in touch with them?
)
[answer] => Array (
[id] => 30
[type] => video
[content] => v-0bd3d270-2f24-0132-cd89-12313914f10b
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 124
[qst] => What year did you start high school? What high school did you go to? Did you like it? Did you ever wish you would've gone to a different high school?
)
[answer] => Array (
[id] => 36
[type] => text
[content] => Started HS in 1987
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 213
[qst] => As a young adult did you stay in the same town as your friends or did you move to a new place and had to make new friends?
)
[answer] => Array (
[id] => 39
[type] => video
[content] => v-7d59df50-3bda-0132-cda7-12313914f10b
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 207
[qst] => After high school - did you go to college, join the miltary, or did you get a job?
)
[answer] => Array (
[id] => 40
[type] => text
[content] => went to college at ASU
[q_type] => life
)
)
)
)
Array (
[Multiple Sclerosis] => Array (
[0] => Array (
[question] => Array (
[id] => 1278
[qst] => Do you know of any potential new drugs or treatments that are in development to treat multiple sclerosis? Are you optomistic?
)
[answer] => Array (
[id] => 33
[type] => text
[content] => vg hjc
[q_type] => pack
)
)
)
)
However, What I would like to do is combine nodes in the array that already exist, like so:
Array (
[Ancestry] => Array (
[0] => Array (
[question] => Array (
[id] => 1
[qst] => Has your family always lived in this country? Where did your family come from? How did they come here?
)
[answer] => Array (
[id] => 28
[type] => text
[content] => idk
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 158
[qst] => Who were your best friends in high school? Were they the same ones from grade school? Do you still keep in touch with them?
)
[answer] => Array (
[id] => 30
[type] => video
[content] => v-0bd3d270-2f24-0132-cd89-12313914f10b
[q_type] => life
)
)
[1] => Array (
[question] => Array (
[id] => 124
[qst] => What year did you start high school? What high school did you go to? Did you like it? Did you ever wish you would've gone to a different high school?
)
[answer] => Array (
[id] => 36
[type] => text
[content] => Started HS in 1987
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 213
[qst] => As a young adult did you stay in the same town as your friends or did you move to a new place and had to make new friends?
)
[answer] => Array (
[id] => 39
[type] => video
[content] => v-7d59df50-3bda-0132-cda7-12313914f10b
[q_type] => life
)
)
[1] => Array (
[question] => Array (
[id] => 207
[qst] => After high school - did you go to college, join the miltary, or did you get a job?
)
[answer] => Array (
[id] => 40
[type] => text
[content] => went to college at ASU
[q_type] => life
)
)
)
)
Array (
[Multiple Sclerosis] => Array (
[0] => Array (
[question] => Array (
[id] => 1278
[qst] => Do you know of any potential new drugs or treatments that are in development to treat multiple sclerosis? Are you optomistic?
)
[answer] => Array (
[id] => 33
[type] => text
[content] => vg hjc
[q_type] => pack
)
)
)
)
How can I modify the code above to do this?
EDIT - Updating to include some of the code I've tried to compress the array:
After the full $allQsts array is created, I looped it through this and tested the output, but each entry was duplicated even more.
$sortedIt = array();
foreach($allQsts as $m => $n){
if(!isset($sortedIt[$m])){
$sortedIt[$m] = array();
}
$sortedIt[$m] = $n;
}
I've also been playing around with array_merge_recursive but have yet to get anywhere close.
Assuming this is run in a loop and $allQsts points to the same array each time, you can simplify the code drastically:
$daField = $cat[$type.'_cat_name'];
$daData = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
if (array_key_exists($daField, $allQsts)) {
$allQsts[$daField][] = $daData;
} else {
$allQsts[$daField] = array($daData);
}
This by itself should be enough to get the desired data structure.

Fetching mysql records from CakePHP with specific index

I am using the following cakephp query to retrieve data from mysql:
$tops = $this->PageBanner->find('all', array(
'conditions' => array(
'PageBanner.status' => 1
),
'fields' => array(
'PageBanner.page_url',
'PageBanner.image',
'PageBanner.logo',
'PageBanner.logo_text',
'PageBanner.content'
)
));
This query returns me the following results:
[0] => Array
(
[PageBanner] => Array
(
[page_url] => index
[image] => home_banner.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
)
[1] => Array
(
[PageBanner] => Array
(
[page_url] => write_review
[image] => kids2.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
)
But I want the data to be returned in the following format:
[index] => Array
(
[page_url] => index
[image] => home_banner.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
[write_review] => Array
(
[page_url] => write_review
[image] => kids2.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
I need page_url field content in place of Array index (e.i. 0, 1). Is that possible to get data in this format or I need to manually configure the arrays?
$result = Set::combine($tops, '{n}.PageBanner.page_url', '{n}.PageBanner');
pr($result);

How to group elements of array using Primary and secondary key?

I've got this array:
Array
(
[0] => Array
(
[id]=>1
[account_id] => 1
[object_id] => 43
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[1] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 42
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[2] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 41
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[3] => Array
(
[id] => 2
[account_id] => 2
[object_id] => 1
[object_type] => USER
[action_type] => FOLLOW_USER
)
[4] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 2
[object_type] => USER
[action_type] => FOLLOW_USER
)
[5] => Array
(
[id] => 1
[account_id] => 1
[object_id] => 1
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
)
Now I want to group elements have same value (for example UPLOAD_PHOTO) by id as Primary Key and action_type as Secondary Key, like:
Array
(
[0] => Array(
[id] => 1
[account_id] => 1
[actions] => array(
[1] => array(
[object_id] => 42
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
[2] => array(
[object_id] => 43
[object_type] => PHOTO
[action_type] => UPLOAD_PHOTO
)
)
)
[2] => Array
(
[id] => 1
[account_id] => 1
[actions] = array(
[0] => Array
(
[object_id] => 3
[object_type] => USER
[action_type] => FOLLOW_USER
)
[1] => Array
(
[object_id] => 4
[object_type] => USER
[action_type] => FOLLOW_USER
)
)
)
)
I tried some solutions but didn't succeed.
When constructing your output array, you'll want to use meaningful array keys. That way you can find the out element that the in element needs to be added to:
$in = (...your array...);
$out = array();
foreach($in as $element) {
$id = $element['id'];
//If that id hasn't been seen yet, create the out element.
if (!isset($out[$id])) {
$out[$id] = array(
'id'=>$element['id'],
'account_id' => $element['account_id'],
'actions' => array()
);
}
//Add that action to the out element
$out[$id]['actions'][] = array(
'object_id' => $element['object_id'],
'object_type' => $element['object_type'],
'action_type' => $element['action_type']
);
}
I'm not sure why your input elements have different fields... If this is a desired feature, where one set of possible fields belongs to the id group and another set belongs to the action, you can do this instead (slightly less readable, but more flexible):
$in = (...your array...);
$out = array();
//These define which fields from an
//input element belong to the id,
//and which to the action.
$id_fields = array_flip(array('id','account_id','object_user_id');
$action_fields = array_flip(array('object_id','object_type','action_type');
foreach($in as $element) {
$id = $element['id'];
//If that id hasn't been seen yet, create the out element.
if (!isset($out[$id])) {
$out[$id] = array_intersect_key($element, $id_fields);
$out[$id]['actions'] = array();
}
//Add that action to the out element
$out[$id]['actions'][] = array_intersect_key($element, $action_fields);
}
This is a better solution if the input elements can be different, because if an expected field (other than 'id') is missing, the script will cope with it easily.

how can i access such a php array

i was trying to access this php array with no luck, i want to access the [icon] => icon.png
Array ( [total] => 2
[total_grouped] => 2
[notifys] => Array ( [0] => Array ( [notifytype_id] => 12
[grouped] => 930
[icon] => icon.png
[n_url] => wall_action.php?id=930
[desc] => 690706096
[text] => Array ( [0] => Sarah O'conner ) [total] => 1 )))
$arr['notifys'][0]['icon']
ETA: I'm not sure what your comment means, the following code:
$arr = array('total'=>2, 'total_grouped' => 2, 'notifys' => array(array(
'notifytype_id' => 12, 'icon' => 'icon.png')));
echo '<pre>';
print_r($arr);
echo '</pre>';
var_dump($arr['notifys'][0]['icon']);
outputs:
Array
(
[total] => 2
[total_grouped] => 2
[notifys] => Array
(
[0] => Array
(
[notifytype_id] => 12
[icon] => icon.png
)
)
)
string(8) "icon.png"
Generally, code never outputs nothing. You should be developing with all errors and notifications on.
$arr['notifys'][0]['icon']
rg = Array ( [total] => 2 [total_grouped] => 2 [notifys] => Array ( [0] => Array ( [notifytype_id] => 12 [grouped] => 930 [icon] => icon.png [n_url] => wall_action.php?id=930 [desc] => 690706096 [text] => Array ( [0] => Sarah O'conner ) [total] => 1 )));
icon = rg["notifsys"][0]["icon"];
Everybody is posting right answer. Its just you have giving a wrong deceleration of array.
Try var_dump/print_r of array and then you can easily understand nodes.
$arr = array(total => 2,
total_grouped => 2,
notifys => array( 0 => array(notifytype_id => 12,
grouped => 930,
icon => 'icon.png',
n_url => 'wall_action.php?id=930',
desc => 690706096,
text =>array(0 => 'Sarah Oconner' ),
total => 1,
),
),
);
echo $arr['notifys']['0']['icon'];

Categories