I have a array that looks like this
Array
(
[11] => Array
(
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 1
[number] => 1
[zone] => 1
[value] => 38
)
)
[12] => Array
(
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 2
[number] => 1
[zone] => 19
[value] => 40
)
)
)
I want to delete the first dimension so that it looks like this
Array
(
[0] => Array
(
[type] => OPT
[panel] => 1
[loop] => 1
[number] => 1
[zone] => 1
[value] => 38
)
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 2
[number] => 1
[zone] => 19
[value] => 40
)
)
How do I do that?
Sorry but I have to put in some test or the compiler won't let me post the code.
You can simply use call_user_func_array as
$result = call_user_func_array('array_merge',$your_array);
Demo
$short = array();
foreach($long as $k=>$v) {
$short[] = $array[$k][0];
}
var_dump($short);
provided that you have only one element in 2nd level
This should work for you:
Just go through each sub array and array_merge() the arrays with your $result together, e.g.
<?php
$result = [];
foreach($arr as $v)
$result = array_merge($result, $v);
print_r($result);
?>
Demo
Related
I have a Array like this
Array
(
[0] => Array
(
[vendor_id] => 2
[vendor_total_order] => 80
)
[1] => Array
(
[vendor_id] => 2
[vendor_total_order] => 100
)
[2] => Array
(
[vendor_id] => 1
[vendor_total_order] => 150
)
[3] => Array
(
[vendor_id] => 3
[vendor_total_order] => 80
)
[4] => Array
(
[vendor_id] => 5
[vendor_total_order] => 150
)
[5] => Array
(
[vendor_id] => 1
[vendor_total_order] => 110
)
)
I want to simplify this array in such a way that if the 'vendor_id' are same for two values there there accumulated/summed value should be assigned to 'vendor_total_order' to that 'vendor_id'(basically we are removing values which are having same vendor_id with the total value of duplicates).
So when i provide the above array as input the output should look like as follow
Array
(
[0] => Array
(
[vendor_id] => 2
[vendor_total_order] => 180
)
[1] => Array
(
[vendor_id] => 1
[vendor_total_order] => 260
)
[2] => Array
(
[vendor_id] => 3
[vendor_total_order] => 80
)
[3] => Array
(
[vendor_id] => 5
[vendor_total_order] => 150
)
)
How can i do this ?
You just need to group them using a foreach. Example:
$total = array();
foreach ($array as $key => $value) {
if(!isset($total[$value['vendor_id']])) {
$total[$value['vendor_id']] = array('vendor_id' => $value['vendor_id'], 'vendor_total_order' => 0);
}
$total[$value['vendor_id']]['vendor_total_order'] += $value['vendor_total_order'];
}
$total = array_values($total); // simple reindex
echo '<pre>';
print_r($total);
Sample Output
Your best bet is to write a custom script that does the following:
Creates an empty new "result" array
Iterates over the current array and for each item:
If the item doesn't exist in result, insert it, otherwise update the total_value value as the sum of it's current value and the new item.
Save the result array
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);
I stuck on this and really don't know how to solve it.
I have two multi-dimensional arrays and need to match every "entry_id" from second array with first one. Then need to check if every "file_no" from second array is in database (first array) and "status" are matched with 1st array . If "status" is different, update second array with string (e.g. updated value) like this:
...
[status] => Array
(
[0] => abc
[1] => defghijk - "updated value"
)
So I have first array from database:
Array
(
[0] => Array
(
[entry_id] => 1
[file_no] => KSBR 40 INS 3674 / 2014
[status] => abc
)
[1] => Array
(
[entry_id] => 9
[file_no] => KSUL 77 INS 18898 / 2013
[status] => abc
)
[2] => Array
(
[entry_id] => 9
[file_no] => KSUL 77 INS 21218 / 2013
[status] => defg
)
)
And second array generated from script:
Array
(
[0] => Array
(
[entry_id] => 1
[id] => 500910/098
[fullname] => Milan Vrtal
[type] => person
[file_no] => Array
(
[0] => KSBR 26 INS 37146 / 2013
[1] => KSBR 40 INS 3674 / 2014
)
[status] => Array
(
[0] => status1
[1] => status2
)
)
[1] => Array
(
[entry_id] => 2
[id] => 46900217
[fullname] => ENTEC a.s.
[type] => company
[file_no] => Array
(
[0] => KSBR 28 INS 1232 / 2013
)
[status] => Array
(
[0] => qwer
)
)
[2] => Array
(
[entry_id] => 9
[fullname] => Blanka Kořínková
[type] => person
[file_no] => Array
(
[0] => KSUL 77 INS 18898 / 2013
[1] => KSUL 77 INS 21218 / 2013
)
[status] => Array
(
[0] => abc
[1] => defghijk
)
)
)
Thanks for every comment and sorry for english :)
This is by creating a temporary array to search in. This will use quite some memory when the arrays are big, but will result in faster execution time...
$tmparr = array();
foreach($arr1 as $arr1_val)
{
//put an new element in $temparr with key 'entry_id' and an array as value
if (!isset($tmparr[$arr1_val['entry_id']]))
$tmparr[$arr1_val['entry_id']] = array();
//add the status to the array
$tmparr[$arr1_val['entry_id']][] = $arr1_val['status'];
}
/*
$tmparr = Array
(
[1] => Array
(
[0] => abc
)
[9] => Array
(
[0] => abc
[1] => defg
)
)
*/
//arr2_val by reference so that we can change it
foreach($arr2 as &$arr2_val)
{
//get the current entry_id
$entry_id = $arr2_val['entry_id'];
//see if this entry_id was in the first array, and if so...
if (isset($tmparr[$entry_id]))
{
//change the status to both the original status and the status of the first array
$arr2_val['status'] = array_merge($arr2_val['status'],$tmparr[$entry_id]);
}
}
print_r($arr2);
Output:
Array
(
[0] => Array
(
[entry_id] => 1
[id] => 500910/098
[fullname] => Milan Vrtal
[type] => person
[file_no] => Array
(
[0] => KSBR 26 INS 37146 / 2013
[1] => KSBR 40 INS 3674 / 2014
)
[status] => Array
(
[0] => status1
[1] => status2
[2] => abc
)
)
[1] => Array
(
[entry_id] => 2
[id] => 46900217
[fullname] => ENTEC a.s.
[type] => company
[file_no] => Array
(
[0] => KSBR 28 INS 1232 / 2013
)
[status] => Array
(
[0] => qwer
)
)
[2] => Array
(
[entry_id] => 9
[fullname] => Blanka Kořínková
[type] => person
[file_no] => Array
(
[0] => KSUL 77 INS 18898 / 2013
[1] => KSUL 77 INS 21218 / 2013
)
[status] => Array
(
[0] => abc
[1] => defghijk
[2] => abc
[3] => defg
)
)
)
edit: This is possible too, whitout the temp array, but with a loop in a loop. This will be slower than the first one, but will consume less memory:
//arr2_val by reference so that we can change it
foreach($arr2 as &$arr2_val)
{
//get the current entry_id
$entry_id = $arr2_val['entry_id'];
//search for the correct row in the first array
foreach($arr1 as $arr1_val)
{
if ($arr1_val['entry_id'] == $arr2_val['entry_id'])
{
$arr2_val['status'][] = $arr1_val['status'];
//a continue should be added here to make it faster...
}
}
}
print_r($arr2);
This should work
foreach($array1 as $i)
{
foreach($array2 as $key=>$j)
{
if($j['entry_id'] == $i['entry_id'])
{
if($array2[$key]['status'] != $i['status'])
{
$j['status'] = array(
$i['status'],
$j['status'] // the new status
);
}
continue;
}
}
}
I found a solution for you :
$a1 = [['entry_id' => 1, 'file_no' => 'KSBR', 'status' => 'abc'], ['entry_id' => 2, 'file_no' => 'KSUL', 'status' => 'defg']];
$a2 = [['entry_id' => 1, 'file_no' => 'KSBR', 'status' => 'abc', 'type' => 'person'], ['entry_id' => 2, 'file_no' => 'KSUL', 'status' => 'defg']];
print_r(new_array_merge_recursive($a1, $a2));
function new_array_merge_recursive(array $array1, array $array2=array())
{
$arrays = func_get_args();
$merge = array_shift($arrays);
foreach ($arrays as $array)
{
foreach ($array as $key => $val)
{
if (is_array($val) && array_key_exists($key, $merge))
{
$val = new_array_merge_recursive((array) $merge[$key], $val);
}
$merge[$key] = $val;
}
}
return $merge;
}
I want to merge two arrays into one array as follows,
Array1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
Expected array result is:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
How to merge these array elements into one array element ?
foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
Where $origArray is your array which is to be merged into and $arrayToBeAdded the array you merge into.
User array_merge_recursive():
$final = array_merge_recursive($array1, $array2);
Try this little known overload of the + operator for arrays:
$result = $array1[0] + $array2[0]
Use function array_merge($array1[0], $array2[0]) . Following is the example for the same
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);
Since you have unique keys, you could use something as simple as the + operator (union)...
For example:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )
For this php has multiple functions. You can use $arrays = array_combine($array1, $array2);.
PHP.net - array_combine
Hope it helped!
and i got a problem (its big for me) :(
ok, i have some array like ...
Array(
[0] => Array
(
[id] => 1
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
[3] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[4] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
how to merge them if the array have same key value ... ?
the result that i need got is like this ...
Array(
[0] => Array
(
[id] => 1
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
)
)
[2] => Array
(
[id] => 2
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
)
)
im very need some help here, and im working on PHP ... what method should i do for this case?
i try too searching on google and in here ... but i dont know the keyword >.<
Many thanks before :)
regard, Stecy
Try like this:
<?php
$result = array();
foreach ($my_array as $v) {
$id = $v['id'];
$result[$id]['id'] = $id;
$result[$id]['detail'][] = array(
'order_sn' => $v['order_sn'],
'total' => $v['total'],
);
}
You can just loop over the array and build a resulting one:
// $a is your array
$r=array();
foreach($a as $v)
$r[$v['id']][]=array('order_sn'=>$v['order_sn'], 'total'=>$v['total']);
echo'<pre>';
var_dump($r);
Since you do the paring by ID, it is wise to have it as the key and all the data associated with it as the value. There's no need to also have id and detail.
foreach($origianlArray as $key => $value){
$newArray[$value['id']]['id'] = $value['id'];
$newArray[$value['id']]['detail'][] = array('order_sn' => $value['order_sn'], 'total' => $value['total']);
}
Check out the PHP array_merge function.