push to a multidimensional array in php - php

I have array that contain an score and id that calculated from other function
And I have user info that retried from DB.
In Both array ID's are the same
how can I push them to One array?
Score Array
Array
(
[0] => Array
(
[id] => 85
[total_cnt] => 2006
)
[1] => Array
(
[id] => 86
[total_cnt] => 1014
)
[2] => Array
(
[id] => 92
[total_cnt] => 6
)
[3] => Array
(
[id] => 93
[total_cnt] => 6
)
)
user info
Array
(
[0] => Array
(
[id] => 52
[user_phone] => 00000000
[user_email] => test#yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
)
[1] => Array
(
[id] => 78
[user_phone] => 000000001
[user_email] => google#gmail.com
[user_name] => google
[user_picture] =>XqWKSDVci.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
)
)
My Desire output
Array
(
[0] => Array
(
[id] => 86 <--Same ID in both arrays
[user_phone] => 00000000
[user_email] => test#yahoo.com
[user_name] => yahoo
[user_picture] =>FG6K7Z3XTc.Pic.jpg
[user_post_hour] => 24
[user_is_block] => 1
[user_reg_date] => 2017-05-16 13:52:35
[total_cnt] => 1014 <-- first array field added
)
I want an optimized code and I won't use loop for to do this
Thanks for your help

Use PHP's built-in function array_merge. Use the official PHP documentation for additional guidance # http://php.net/manual/en/function.array-merge.php

Update:
A much better approach seems to be "array_column":
$cnts = array_column($scores, 'total_cnt', 'id');
foreach ($userInfo as $key => $item) {
$userInfo[$key]['total_cnt'] = $cnts[$item['id']];
}
I made some "naive" benchmark tests using microtime() and test data like your arrays:
Execution times:
10000 items in both arrays:
array_column 0.005s vs 0.85s foreach
20000 items in both arrays:
array_column 0.011s vs 18s foreach
Original answer:
You can also use foreach loops like this:
foreach ($userInfo as $userKey => $item) {
foreach ($scores as $scoreKey => $score) {
if ($score['id'] == $item['id']) {
$userInfo[$userKey]['total_cnt'] = $score['total_cnt'];
unset($scores[$scoreKey]);
break;
}
}
}
The unset within the second loop "removes" the processed score from the $scores array to reduce the number of iteration cycles in the next run. Please note that the $scores array will be empty afterwards, maybe create a copy of it and work with that.

Related

Sorting an array with similar values

I have an array of arrays that contains a date string.
I'd like to sort these arrays by this date.
What seems to be the monkeywrench in this is that some of the arrays share the same value for the date field as well as similar values for tid and/or thing and/or other_thing.
Array (
[0] => Array (
[tid] => 44
[date] => 1442905200
[thing] => 2J5265B
[other_thing] => Scoop
)
[1] => Array (
[tid] => 47
[date] => 1442905200
[thing] => 2J5265B
[other_thing] => Scoop
)
[2] => Array (
[tid] => 48
[date] => 1430031600
[thing] => 2E5116A
[other_thing] => shower
)
[3] => Array (
[tid] => 46
[date] => 1430031600
[thing] => 2E5116A
[other_thing] => shower
)
[4] => Array (
[tid] => 80
[date] => 1464246000
[thing] => 7J6147A
[other_thing] => shower
)
[5] => Array (
[tid] => 47
[date] => 1442905200
[thing] => 2J5265B
[other_thing] => TTT
)
[6] => Array (
[tid] => 44
[date] => 1442905200
[thing] => 2J5265B
[other_thing] => TTT
)
[7] => Array (
[tid] => 46
[date] => 1504594800
[thing] => 2J7248A
[other_thing] => shower
)
[8] => Array (
[tid] => 45
[date] => 1513238400
[thing] => 2J7348C
[other_thing] => TTT
)
)
That's what I'd like to do.
I'd like to sort this array.
You should consider using usort() (Docs). This function allows you to specify a comparator to have a user-defined sorting algorithm.
The resulting code might look like this:
function cmp($a, $b)
{
return $b['date'] - $a['date'];
}
usort($your_array, "cmp");
One fast forward solution would be to use the date as a key of the array while the array is being build and then you can simply sort keys using PHP ksort().
To avoid keys duplicity check if the key is set to handle such situations.
// building the data array from database or so
$array = array(); // the array to be sorted
$duplicity = array(); // track the duplicity date records
foreach ($data as $key => $value) {
$counter = 0;
#$duplicity[$value['date']]++; // suppressing notices
$array[$value['date'].'_'.$duplicity[$value['date']]] = $value;
}
ksort($array); // sort array by keys
print_r($array); // just check the sorted array
Demo: https://eval.in/978160
More sorting functions Sorting arrays

Merge two 2d arrays according to a shared column value and modify keys while appending elements

I have the following two arrays of objects:
First Array: $array1
Array
(
[0] => Array
(
[match] => 1
[when] => 2013-10-13 15:00:00
[a] => AD
[b] => NiP
[winner] => c
[closed] => 1
[event] => Fragbite Masters
[format] => 3
)
[1] => Array
(
[match] => 2
[when] => 2013-10-13 15:00:00
[a] => VG
[b] => AD
[winner] => a
[closed] => 1
[event] => Starseries
[format] => 5
)
[2] => Array
(
[match] => 3
[when] => 2013-10-13 21:15:00
[a] => Serbia
[b] => Portugal
[winner] => a
[closed] => 1
[event] => ESEC
[format] => 1
)
)
Second Array: $array2
Array
(
[0] => Array
(
[match] => 1
[a] => 58
[b] => 107
)
[1] => Array
(
[match] => 2
[a] => 174
[b] => 162
)
[2] => Array
(
[match] => 3
[a] => 64
[b] => 59
)
)
I would like to get something like this:
Array
(
[0] => Array
(
[match] => 1
[when] => 2013-10-13 15:00:00
[a] => AD
[b] => NiP
[winner] => c
[closed] => 1
[event] => Fragbite Masters
[format] => 3
[per_a] => 58
[per_b] => 107
)
[1] => Array
(
[match] => 2
[when] => 2013-10-13 15:00:00
[a] => VG
[b] => AD
[winner] => a
[closed] => 1
[event] => Starseries
[format] => 5
[per_a] => 174
[per_b] => 162
)
[2] => Array
(
[match] => 3
[when] => 2013-10-13 21:15:00
[a] => Serbia
[b] => Portugal
[winner] => a
[closed] => 1
[event] => ESEC
[format] => 1
[per_a] => 64
[per_b] => 59
)
)
Where the key name [a] and [b] from the second array have been modified to [per_a] and [per_b].
Things i tried to merge both files:
array_merge & array_merge_recursive: both get me a result where the merged values of $array2 are appended to the end of $array1.
array_combine: Wont work because $array1 and $array2 haven't an equal number of elements.
This is just a part of each file, both are not equal in term of elements.
If you have an answer for me it would be apreciated ! thx in advance !
Try this you need to modify your keys in function. see Demo
$match : will check key exists in both arrays. $whereKey1
$whereKey2 : pick up the values from second array and put it in your
new key which $newkey1 and $newkey2
function key_compare_func($arr1, $arr2)
{
$newarray = array();
$match = "match";
$whereKey1 = "a";
$whereKey2 = "b";
$newKey1 = "per_a";
$newKey2 = "per_b";
if(is_array($arr1) && is_array($arr2)){
if($arr1[$match] == $arr2[$match] ){
$newarray = array_merge($arr1, array($newKey1 => $arr2[$whereKey1], $newKey2 => $arr2[$whereKey2]));
}
}
return $newarray;
}
$modifiedArray = array_map("key_compare_func",$A1, $A2);
echo '<pre>';print_r($modifiedArray);echo '</pre>';
Output:
[0] => Array
(
[match] => 1
[when] => 2013-10-13 15:00:00
[a] => AD
[b] => NiP
[winner] => c
[closed] => 1
[event] => Fragbite Masters
[format] => 3
[per_a] => 58
[per_b] => 107
)
[1] => Array
(
[match] => 2
[when] => 2013-10-13 15:00:00
[a] => VG
[b] => AD
[winner] => a
[closed] => 1
[event] => Starseries
[format] => 5
[per_a] => 174
[per_b] => 162
)
Assuming that your second array only hold unique match ids, then you can use it as a lookup array after applying the match values as first level keys. array_column() makes this task very simple.
Then simply iterate the over the rows in the first array (modifying by reference so that changes to rows are applied to the original array).
Using this technique, it won't matter if the corresponding rows between the two arrays have different original first level keys (the same cannot be said for #Noman's answer which requires each row from the first array to have a cooresponding row with the exact same position in the second array).
Code: (Demo)
$lookup = array_column($A2, null, 'match');
foreach ($A1 as &$row) {
if (isset($lookup[$row['match']])) {
$row['per_a'] = $lookup[$row['match']]['a'];
$row['per_b'] = $lookup[$row['match']]['b'];
}
}
var_export($A1);

How insert array value in each index of another array in php?

I am having two arrays, in that i need to insert the each index of last key and value of another array keys, values in php. My sample arrays are given below. I am using codeigniter framework.
First array:
Array
(
[0] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Bacardi Rum
[quantity] => 1
[unit_price] => 25.00
[inv_discount] => 0.00
[salesman_id] => 25,27
)
[1] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Baileys
[quantity] => 1
[unit_price] => 15.00
[inv_discount] => 0.00
[salesman_id] => 28,29
)
)
Second array:
Array
(
[0] => 140140,150150
[1] => 151151,05180518
)
And i need the o/p :
Array
(
[0] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Bacardi Rum
[quantity] => 1
[unit_price] => 25.00
[inv_discount] => 0.00
[salesman_id] => 25,27
[salesman] => 140140,150150
)
[1] => stdClass Object
(
[customer_name] => Cash
[ordernumber] => 6452424
[product_name] => Baileys
[quantity] => 1
[unit_price] => 15.00
[inv_discount] => 0.00
[salesman_id] => 28,29
[salesman] => 151151,05180518
)
)
Can any one help me, give some ideas to solve this.
In this case, you have an array of objects (stdClass type) and one other array only. Answering your question you just have to do the code as shown below.
foreach ($secondArray as $key => $value) {
$firstArray[$key]->salesman = $value;
}
or
foreach ($firstArray as $key => $object) {
$object->salesman = $firstArray[$key];
}
foreach($arrA as $key=>$val){
$arrA[$key]['salesman'] = $arrB[$key];
}
As long as both arrays will be same size, array_map will be suitable:
$resultArray = array_map(function ($rowA, $rowB) {
$rowA->salesman = $rowB;
return $rowA;
}, $firstArray, $secondArray);

Flatten Nested Array to a certain Key

I have a data structure like this
Array
(
[0] => Array
(
[actionResult] => Array
(
[show_page] => Array
(
[15] => Array
(
[section_page_id] => 15
[metadata_id] => 62
[section_id] => 7
[display_order] => 0
[current_layout] => 15
[behaviors] => a:1:{i:0;a:1:{i:0;a:0:{}}}
[options] => a:1:{s:13:"defaultLayout";i:63;}
[section_title] => Ask Study
)
[16] => Array
(
[section_page_id] => 16
[metadata_id] => 66
[section_id] => 7
[display_order] => 1
[current_layout] => 16
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:67;}
[section_title] => Ask Study
)
[17] => Array
(
[section_page_id] => 17
[metadata_id] => 69
[section_id] => 7
[display_order] => 2
[current_layout] => 17
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:70;}
[section_title] => Ask Study
)
[18] => Array
(
[section_page_id] => 18
[metadata_id] => 72
[section_id] => 7
[display_order] => 3
[current_layout] => 18
[behaviors] => a:0:{}
[options] => a:1:{s:13:"defaultLayout";i:73;}
[section_title] => Ask Study
)
)
)
)
[1] => Array
(
[actionResult] => Array
(
[view_page] => 18
)
)
)
What i need is the ability to flatten this to an array structure to a point where it stops at "actionResult" where all the actionResult will become ONE array rather than nested like this...
How can I go about by doing this in PHP???
if i have understood what you want correctly this should work:
$arr2=array();
foreach($arr as $tmp){
foreach($tmp as $actionRequest){
foreach($actionRequest as $key=>$val){
$arr2[$key]=$val;
}
}
}
where $arr is what you already have and $arr2 will be an array including 2 values , Show_Page and view_page
Best solution is:
$new_arr = array_map(function ($a) {
return $a['actionResult'];
}, $old_arr);

comparing array value from multidimensional array with index

I have a multidimensional array that loks lik this:
Array
(
[0] => Array
(
[name] => >chr1:2198584545754_genome_1000+
[score] => 511
[hit] => 50
)
[1] => Array
(
[name] => >chr2:2198581212154_genome_1000+
[score] => 620
[hit] => 80
)
[2] => Array
(
[name] => >chr3:2115151215754_genome_1000+
[score] => 666
[hit] => 90
)
[3] => Array
(
[name] => >chr4:2198584545754_genome_1000+
[score] => 750
[hit] => 50
)
[4] => Array
(
[name] => >chr5:1218455145754_genome_1000+
[score] => 800
[hit] => 100
)
[5] => Array
(
[name] => >chr6:1231354645454_genome_1000+
[score] => 850
[hit] => 110
)
[6] => Array
(
[name] => >chr7:1231213211134_genome_1000+
[score] => 900
[hit] => 120
)
)
I have a foreach loop which will loop through each letter of a random sequence and use the index to give each letter a number value.
If the value of ['hit'] matches the index value of the random sequence
i want to insert a function.
I cannot figure this out. I think my problem is in callng each value of ['hit'] and comparing with index. Does anyone know how to do this ?
thanks
To put DaveRandom's comment into an answer (with minor amends):
foreach ($outerArray as $index => $innerArray)
{
if($innerArray['hit'] === $index)
{
doSomething();
}
}
#DaveRandom - feel free to delete or re-post this as your own answer if I'm posting out of turn here...
foreach ($array as $key) {
if ($key['hit'] == $index)
{
// you function or logic here
}
}

Categories