How do i merge the arrays in a particular format? - php

I have following arrays:
1) for total placed
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalplaced] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalplaced] => 1
)
)
)
2) for total working
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totalworking] => 4
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totalworking] => 1
)
)
)
3) for total trained
Array
(
[0] => Array
(
[centers] => Array
(
[name] => delhi
[id] => 1
)
[0] => Array
(
[totaltrained] => 8
)
)
[1] => Array
(
[centers] => Array
(
[name] => mumbai
[id] => 2
)
[0] => Array
(
[totaltrained] => 1
)
)
)
I wanted to merge these arrays so that the resultant array should look like this
[newarray] => Array(
[0] => Array (
[centers] => Array
(
[name] => delhi
[id] => 1
[totalplaced] => 8
[totalworking] => 4
[totaltrained] => 8
)
)
[1]=> Array(
[centers] => Array
(
[name] => mumbai
[id] => 2
[totalplaced] => 1
[totalworking] => 1
[totaltrained] => 1
)
)
)
This is the tabular representation of the above data which i want to display
centername totalplaced totalworking totaltrained
delhi 8 4 8
mumbai 1 1 1
Please help me on this.
Thanks
Pankaj Khurana

The difficulty here is that PHP's functions such as array_merge() and array_merge_recursive() will not merge data into numeric keys, but rather will re-key any duplicate numeric key. So for example given two arrays:
array(
'test' => 'abc',
0 => 'xyz'
);
array(
'test' => 'def',
0 => 'uvw'
);
Merging them together with array_merge() will produce an array like:
array(
'test' => 'def',
0 => 'xyz',
1 => 'uvw'
);
So, you need a custom function to be "additive" on any key, regardless of whether it is a string or numeric key. Try this:
function mixed_key_array_merge() {
$args = func_get_args();
$result = array();
foreach ($args as $arg) {
// discard non-array arguments; maybe this could be better handled
if (!is_array($arg)) {
continue;
}
foreach ($arg as $key => $value) {
if (!isset($result[$key])) {
$result[$key] = $value;
} else if (is_array($result[$key])) {
$result[$key] = call_user_func_array('mixed_key_array_merge',array($result[$key],$value));
}
}
}
return $result;
}

Related

Split the array in to sub arrays based on array key value [duplicate]

This question already has answers here:
How to group subarrays by a column value?
(20 answers)
Closed 1 year ago.
I am facing one issue while splitting array by key value. My array looks like below :-
Array
(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
[1] => Array
(
[product_id] => 1
[brand_id] => 1
)
[2] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
Now i want to filter split the array based on brand_id. My expected output is like below:-
Array(
[0] => Array(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
)
[1] => Array(
[0] => Array
(
[product_id] => 1
[brand_id] => 1
)
[1] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
)
My Input array is stored in $proArray variable
My attempt below:-
$brands = array();
foreach ($proArr as $key => $pro) {
$brands[] = $pro['brand_id'];
}
$brands = array_unique($brands);
$ckey = 0;
foreach($brands as $brand){
}
One way to do it with simple foreach() loop to push values based on your brand_id like below-
$key = 'brand_id';
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
print_r($return);
WORKING DEMO: https://3v4l.org/bHuWV
Code:
$arr = array(
array(
'product_id' => 6,
'brand_id' => 2
),
array(
'product_id' => 1,
'brand_id' => 1
),
array(
'product_id' => 5,
'brand_id' => 1
)
);
$res = [];
foreach ($arr as $key => $value)
$res[$value['brand_id']][] = $value;
$res = [...$res];
print_r($res);
Output:
Array
(
[0] => Array
(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
)
[1] => Array
(
[0] => Array
(
[product_id] => 1
[brand_id] => 1
)
[1] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
)

merge two array values

How can I make this array:
Array
(
[0] => Array
(
[id] => 3412341233214
[number] => 21000
)
[1] => Array
(
[id] => 12121212121212
[number] => 18000
)
[2] => Array
(
[id] => 12121212121212
[number] => 17000
)
)
Look like the one below, where [1] and [2] have been merged into a single array based on having the same id and the number has been added together.
Array
(
[0] => Array
(
[id] => 3412341233214
[number] => 21000
)
[1] => Array
(
[id] => 12121212121212
[number] => 35000
)
)
Create a $tmp array the store the number property in it.
Only store it if the id doesn't exist yet using:
if(!isset($tmp[$obj['id']]))
To make each value unique
After that, count the $tmp number with the $array number.
$tmp[$obj['id']]['number'] += $obj['number'];
https://3v4l.org/UMJ4p
$array = array(
0 => array(
"id" => 3412341233214,
"number" => 21000
),
1 => array(
"id" => 12121212121212,
"number" => 18000
),
2 => array(
"id" => 12121212121212,
"number" => 17000
)
);
$tmp = Array();
foreach($array as $obj) {
if(!isset($tmp[$obj['id']])) {
$tmp[$obj['id']] = array_merge(Array('number'=>1),$obj);
continue;
}
$tmp[$obj['id']]['number'] += $obj['number'];
}
print_r(array_values($tmp));
The following code results into
(
[0] => Array
(
[number] => 21000
[id] => 3412341233214
)
[1] => Array
(
[number] => 35000
[id] => 12121212121212
)
)

Compare items within an array without loosing information [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 6 years ago.
I have an array of product information. I have a loop that runs through the array and compares the prices to find the lowest one.
$rows = get_field('variations',$product_id);
if($rows){
$prices = array();
foreach($rows as $row){
$prices[] = $row['variation_price'];
}
//Getting the lowest price from the array
$lowest_price = min($prices);
}
echo $lowest_price;
However I now need to get the other information that is associated with the "lowest price" array set. IE. I need the ID of the lowest price product etc.
Any help is welcome!
Here is a dump of the array
Array
(
[0] => Array
(
[] =>
[variation_title] => Small Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 7
[variation_subscription_cycle] => /month
[variation_id] => 405
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 1 Domain
)
[1] => Array
(
[custom_field] => 1 Million QPM
)
[2] => Array
(
[custom_field] => 50 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] =>
)
[1] => Array
(
[] =>
[variation_title] => Medium Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 35
[variation_subscription_cycle] => /month
[variation_id] => 286
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 10 Domains
)
[1] => Array
(
[custom_field] => 5 Million QPM
)
[2] => Array
(
[custom_field] => 500 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] => ribbon
)
[2] => Array
(
[] =>
[variation_title] => Large Business
[checkout] => cart
[trial] => Array
(
[0] => trial
)
[variation_price] => 100
[variation_subscription_cycle] => /month
[variation_id] => 406
[variation_url] =>
[custom] => Array
(
[0] => Array
(
[custom_field] => 50 Domains
)
[1] => Array
(
[custom_field] => 15 Million QPM
)
[2] => Array
(
[custom_field] => 1,,500 Records
)
[3] => Array
(
[custom_field] => DNS Alias
)
)
[css_styles] =>
)
)
<?php
class Test {
public $a;
public $b;
public function __construct($a1,$b1)
{
$this->a = $a1;
$this->b = $b1;
}
}
$first = new test(1,12);
$second = new test(4,25);
$third = new test(7,9);
$values = [$first, $second, $third];
function compare (Test $firstObject, Test $secondObject) {
return $firstObject->a > $secondObject->a;
}
usort($values, "compare");
var_dump($values);
?>

count same categories from array and Store in new array with its count and category name

I have one array which I am getting from database query response.
Now I want to count same categories and print in option_name array.
I have tried it with different array functions but want get desire output.
I have one idea to take new array and push it with foreach loop but not much idea of how can i achieve using code. Please help me to solve it.
Array
(
[0] => Array
(
[CNC] => Array
(
[id] => 5
[category_id] => 68
)
[GVO] => Array
(
[option_name] => Actors
)
)
[1] => Array
(
[CNC] => Array
(
[id] => 11
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[2] => Array
(
[CNC] => Array
(
[id] => 3
[category_id] => 72
)
[GVO] => Array
(
[option_name] => Cricketers
)
)
[3] => Array
(
[CNC] => Array
(
[id] => 4
[category_id] => 74
)
[GVO] => Array
(
[option_name] => Musician
)
)
[4] => Array
(
[CNC] => Array
(
[id] => 7
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
[5] => Array
(
[CNC] => Array
(
[id] => 6
[category_id] => 76
)
[GVO] => Array
(
[option_name] => Directors
)
)
)
Desire Output:
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)
Thanks in advance!
You simply need to loop through the array using foreach like as
$result = [];
foreach($arr as $k => $v){
if(isset($result[$v['GVO']['option_name']])){
$result[$v['GVO']['option_name']] += 1;
}else{
$result[$v['GVO']['option_name']] = 1;
}
}
print_R($result);
You can count the option_name values by incrementing a counter in an associative array where the key is the option_name:
$counts = [];
foreach($array as $v) {
if(!isset($counts[$v['GVO']['option_name']])) {
$counts[$v['GVO']['option_name']] = 0;
}
$counts[$v['GVO']['option_name']]++;
}
print_r($counts);
Try this:
$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
if(in_array($value, $new_array)){
$new_array[$value] = $new_array[$value]+1;
}else{
$new_array[$value] = 1;
}
}
Output
Array
(
[Actors] => 1
[Cricketers] => 2
[Musician] => 1
[Directors] => 2
)

How can I use ksort to sort multiple arrays within an array using PHP? [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 8 years ago.
I've trawled a lot of questions and php manual, but I can't find a way to get sort this data in a graceful way. There may not be, but I'll settle for non-graceful.
At the moment I have a page that builds 4 arrays with data from post. The number of keys changes depending on the input;
// Grab the Tasks
$arraytask = $_POST["task"];
// Grab the Relusers
$arrayreluser = $_POST["reluser"];
// Grab the Usernames
$arrayuser = $_POST["user"];
// Grab the License Types
$arraylicense = $_POST["license"];
$result = array();
foreach( $arraytask as $key => $val) {
$result[] = array('key'=>$key, 'value'=>$val);
}
foreach( $arrayreluser as $key => $val) {
$result[] = array('key'=>$key, 'value'=>$val);
}
foreach( $arrayuser as $key => $val) {
$result[] = array('key'=>$key, 'value'=>$val);
}
foreach( $arraylicense as $key => $val) {
$result[] = array('key'=>$key, 'value'=>$val);
}
ksort($result); // I know this does nothing, I was hoping it would recursively sort or something
At the moment, the output on an example submission looks like (and sorry for the long formatting):
print_r($result);
Array (
[0] => Array (
[key] => 0
[value] => 123 )
[1] => Array (
[key] => 1
[value] => 456 )
[2] => Array (
[key] => 2
[value] => 789 )
[3] => Array (
[key] => 0
[value] => qwe )
[4] => Array (
[key] => 1
[value] => rty )
[5] => Array (
[key] => 2
[value] => uio )
[6] => Array (
[key] => 0
[value] => asd )
[7] => Array (
[key] => 1
[value] => fgh )
[8] => Array (
[key] => 2
[value] => jkl )
[9] => Array (
[key] => 0
[value] => license 1 )
[10] => Array (
[key] => 1
[value] => license 2 )
[11] => Array (
[key] => 2
[value] => license 3 )
)
However I want the output to be like
print_r($result);
Array (
[0] => Array (
[key] => 0
[value] => 123 )
[3] => Array (
[key] => 0
[value] => qwe )
[6] => Array (
[key] => 0
[value] => asd )
[9] => Array (
[key] => 0
[value] => license 1 )
[1] => Array (
[key] => 1
[value] => 456 )
[4] => Array (
[key] => 1
[value] => rty )
[7] => Array (
[key] => 1
[value] => fgh )
[10] => Array (
[key] => 1
[value] => license 2 )
[2] => Array (
[key] => 2
[value] => 789 )
[5] => Array (
[key] => 2
[value] => uio )
[8] => Array (
[key] => 2
[value] => jkl )
[11] => Array (
[key] => 2
[value] => license 3 )
)
I know I'm sorting Arrays by their keys... I just can't think of a better way to sort this data.
At the moment I've looked at array_merge() which seems to overwrite duplicate keys, and I've tried a few variations of foreach loops which have just ended in tears for everyone involved.
An alternative way to ask this question would be "If I can't sort these arrays by the keys within them, can I merge my 4 arrays so that the values of each array compile in to a single array, based off key?"
An acceptable (seemingly more graceful) output would also be
Array (
[0] => Array (
[key] => 0
[value] => 123, qwe, asd, license 1 )
[1] => Array (
[key] => 1
[value] => 456, rty, fgh, license 2 )
[2] => Array (
[key] => 2
[value] => 789, uio, jkl, license 3 )
)
I'm just not sure I can append values to keys in an array, if I do not explicitly know how many keys there are.
Postscript: if there are typos here, that's because this is the example cut down from the actual code for clarity, and I'm sorry. My issue isn't typos.
::SOLUTION::
Thanks to vstm, this worked for combining multiple arrays into a more useful array data;
$result = array();
foreach($arraytask as $key => $val) {
$result[] = array(
'key' => $key,
'task' => $arraytask[$key],
'reluser' => $arrayreluser[$key],
'user' => $arrayuser[$key],
'license' => $arraylicense[$key],
'value' => implode(', ', array(
$arraytask[$key],
$arrayreluser[$key],
$arrayuser[$key],
$arraylicense[$key],
))
);
}
Shows the output as
Array (
[0] => Array (
[key] => 0
[task] => 123
[reluser] => qwe
[user] => asd
[license] => license 1
[value] => 123, qwe, asd, license 1 )
[1] => Array (
[key] => 1
[task] => 456
[reluser] => rty
[user] => fgh
[license] => license 2
[value] => 456, rty, fgh, license 2 ) )
Well it seems that your input data is already given in a way that would make sorting useless. Try it this way:
// Grab the Tasks
$arraytask = $_POST["task"];
// Grab the Relusers
$arrayreluser = $_POST["reluser"];
// Grab the Usernames
$arrayuser = $_POST["user"];
// Grab the License Types
$arraylicense = $_POST["license"];
$result = array();
foreach($arraytask as $key => $val) {
$result[] = array(
'key' => $key,
'task' => $arraytask[$key],
'reluser' => $arrayreluser[$key],
'user' => $arrayuser[$key],
'license' => $arraylicense[$key],
'value' => implode(', ', array(
$arraytask[$key],
$arrayreluser[$key],
$arrayuser[$key],
$arraylicense[$key],
))
);
}
Now you have your "seemingly graceful" output, plus access to all the fields which you might need for working with your data. No need for sorting.
Try by usort(). Example here...
function sortByValue($a, $b) {
return $a['key'] - $b['key'];
}
usort($arr, 'sortByValue');
print '<pre>';
print_r($arr);

Categories