Merge multidimensional PHP arrays - php

From this foreach:
foreach ($statisticheProdotti as $values) {
$prod[] = $values['nome'];
$nomi = array_values(array_unique($prod, SORT_REGULAR));
$arr = array_combine(range(1, 12), range(1, 12));
foreach ($arr as $key => $val) {
$data = ($val == $values['mese']) ? $values['data'] : 0;
$arr[$val] = $data;
}
$prodotti[] = ['name' => $values['nome'], 'data' => array_values($arr)];
}
I get this array:
array (size=14)
0 =>
array (size=2)
'name' => string 'COMBIART PLUS' (length=13)
'data' =>
array (size=12)
0 => string '92' (length=2)
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => int 0
1 =>
array (size=2)
'name' => string 'COMBIART PLUS' (length=13)
'data' =>
array (size=12)
0 => int 0
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => string '92' (length=2)
2 =>
array (size=2)
'name' => string 'SECUR' (length=10)
'data' =>
array (size=12)
0 => string '5' (length=1)
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => int 0
3 =>
.....`
I need to remove duplicated name and have unique array data.
Final output should be (example from index 0 and 1 which have same 'name'):
['name' => 'COMBIART PLUS', 'data' => [92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92]].
I hope I've well explained my problem.
Thanks

Sorry it's taken me a while to respond to this.
This might not be the most elegant way to do this, but assuming you want to combine the arrays with the same name, and combine the data array to make a unique array by using the values and the keys (assuming zero is not useful here), you can do something like this:
$output = array();
foreach ($example as $data) {
// Use the name as a quick array key reference to avoid having to search a second level of the array
$key = $data['name'];
if (!array_key_exists($key, $output)) {
// Instantiate the first entry using the name as the array key (we can reset this later)
$output[$key] = array(
'name' => $key,
'data' => $data['data']
);
// Skip the rest of this loop
continue;
}
// An entry already exists for the name, so merge any unique values into the array using the
// keys AND values to determine if something is unique. Zero is treated as empty.
foreach ($data['data'] as $newKey => $newValue) {
if (empty($output[$key]['data'][$newKey])) {
// Add a new unique entry to the output array (zero counts as empty here)
$output[$key]['data'][$newKey] = $newValue;
}
}
}
// Remove the name from the keys now
$output = array_values($output);
This should give you the result you're after. Example here.

thanks for your help scrowler, thanks to your code I have been able to get what I needed but I've just changed something to adapt it to my project...
function generateChartData($array) {
$prodArr = [];
$oldProd = '';
$arr = array_fill(0, 12, 0);
foreach ($array as $values) {
$Prod = $values['name'];
if ($Prod !== $oldProd) {
if (!empty($oldProd)) {
$prodotti[] = ['name' => $oldProd, 'data' => $arr];
}
$oldProd = $Prod;
}
foreach ($arr as $key => $val) {
if ($key == $values['mese'] - 1) {
$arr[$key] = (int) $values['data'];
}
}
}
// get last item
if (!empty($oldProd)) {
$prodArr[] = ['name' => $oldProd, 'data' => $arr];
}
return $prodArr;
}

Related

How to remove doubles element in foreach loop and keep date assigned to original?

What I am trying to get is to remove duplicate values in the Rest field, but I want to assign / keep its date in the original. element:
array (size=413)
0 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520980
'Rest' => 123abc
1 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520981
'Rest' => qwe123
2 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520983
'Rest' => qwe123
I try it but it doesn't work
public function find_repeats($arr)
{
foreach(array_column($arr, 'Rest') as $ckey=>$value) {
$keys = array_reverse(array_keys(array_column($arr, 'Rest'), $value));
foreach ($keys as $v) {
if ($ckey != $v && isset($arr[$v]))
{
$arr[$ckey]['Date'][] = $arr[$v]['Date'][0];
unset($arr[$v]);
}
}
}
return $arr;
}
This is what the table should look like after this operation
array (size=413)
0 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520980
'Rest' => 123abc
1 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520981
1 => int 1588520983
'Rest' => qwe123
Thanks for help! :)
Simple solution without all these stacked functions:
$newData = [];
foreach ($arr as $item) {
$rest = $item['Rest'];
if (!isset($newData[$rest])) {
$newData[$rest] = $item;
} else {
$newData[$rest]['Date'][] = $item['Date'][0];
}
}
// optionally apply array_values to get 0-indexed array:
$newData = array_values($newData);

How to store a binary tree as one-dimensional array?

How to construct data into a binary tree sort to output a one-dimensional array?
Now that I have constructed the data into a binary tree, how can I recursively solve the binary tree as a one-dimensional array with the following code and data:
Data
$nodes = array(8,3,10,1,6,14,4,7,13);
Construct a binary tree code
function insertNode($node,$newNode){
//var_dump($node);
//var_dump($newNode);
//exit;
if ($node['key'] < $newNode['key']){
if (empty($node['right'])){
$node['right'] = $newNode;
}else{
$node['right'] = insertNode($node['right'],$newNode);
}
}elseif ($node['key'] > $newNode['key']){
if (empty($node['left'])){
$node['left'] = $newNode;
}else{
$node['left'] = insertNode($node['left'],$newNode);
}
}
return $node;
}
function tree($nodes)
{
$node = [
'key' => '',
'left' => '',
'right' => ''
];
$newNode = [
'key' => '',
'left' => '',
'right'=> ''
];
foreach ($nodes as $key => $value){
//insert($value,$key);
if($key == 0)
{
$node['key'] = $value;
continue;
}
$newNode['key'] = $value;
//Constructing a binary tree
$node = insertNode($node,$newNode);
}
//Recursive solution
$node = midSortNode($node);
return $node;
}
var_dump(tree($nodes));
The following is my constructed binary tree
array (size=3)
'key' => int 8
'left' =>
array (size=3)
'key' => int 3
'left' =>
array (size=3)
'key' => int 1
'left' => string '' (length=0)
'right' => string '' (length=0)
'right' =>
array (size=3)
'key' => int 6
'left' =>
array (size=3)
...
'right' =>
array (size=3)
...
'right' =>
array (size=3)
'key' => int 10
'left' => string '' (length=0)
'right' =>
array (size=3)
'key' => int 14
'left' =>
array (size=3)
...
'right' => string '' (length=0)
I need to recursively classify the binary tree into a well-ordered one-dimensional array.
My code is as follows
function midSortNode($node){
$sortArr = [];
if (!empty($node)){
$sortArr[] = midSortNode($node['left']);
//$sortArr['left'] = midSortNode($node['left']);
array_push($sortArr,$node['key']);
$sortArr[] = midSortNode($node['right']);
//$sortArr['right'] = midSortNode($node['right']);
}
return $sortArr;
}
var_dump(midSortNode($node));
Here is the result, but not what I want
0 =>
array (size=3)
0 =>
array (size=3)
0 =>
array (size=0)
...
1 => int 1
2 =>
array (size=0)
...
1 => int 3
2 =>
array (size=3)
0 =>
array (size=3)
...
1 => int 6
2 =>
array (size=3)
...
1 => int 8
2 =>
array (size=3)
0 =>
array (size=0)
empty
1 => int 10
2 =>
array (size=3)
0 =>
array (size=3)
...
1 => int 14
2 =>
array (size=0)
...
How to solve the binary tree as follows
array (size=9)
0 => int 1
1 => int 3
2 => int 4
3 => int 6
4 => int 7
5 => int 8
6 => int 10
7 => int 13
8 => int 14
I'm assuming that your happy with the steps so far, so the main code as it is isn't changed. All I think you need to do is to extract the data from the final tree into a 1 dimensional array. As the items are all leaf nodes and in order, you can just use array_walk_recursive() to go over all of the nodes and add them to a new array...
$tree = tree($nodes);
array_walk_recursive( $tree,
function ($data) use (&$output) { $output[] = $data;} );
print_r($output);
gives...
Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 6
[4] => 7
[5] => 8
[6] => 10
[7] => 13
[8] => 14
)
Edit:
To update the existing code to do this, you can change the midSortNode() to pass around the list of outputs and only add in the current node...
function midSortNode($node, $sortArr = []){
if (!empty($node)){
$sortArr = midSortNode($node['left'], $sortArr);
$sortArr[] = $node['key'];
$sortArr = midSortNode($node['right'], $sortArr);
}
return $sortArr;
}

Adding Array of values to a multidimentional Array in PHP

I would like to add values from a $secondArray to $firstArray:
$firstArray = [
0 => [
'prodID' => 101,
'enabled' => 1,
],
1 => [
'prodID' => 105,
'enabled' => 0,
],
];
The $secondArray will always have the same amount of array items and will be in the same order as the $firstArray:
$secondArray = [34, 99];
This is what I have tried but I keep getting the wrong stockQT values after the exercise:
foreach ($secondArray as $value) {
foreach ($firstArray as &$firstArray) {
$firstArray['stockQT'] = $value;
}
}
Incorrect Result for a var_dump($firstArray):
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 99
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99
I have looked at similar posts but cant seem to get the correct vales after using different suggestions like while() loops. Below is what I need the $firstArray to look like:
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 34
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99
You just need one foreach() using the key since $secondArray will always have the same amount of array items and will be in the same order as the $firstArray. Notice the & to modify the actual value in the array:
foreach($firstArray as $key => &$value) {
$value['stockQT'] = $secondArray[$key];
}
Or alternately loop $secondArray and use the key to modify $firstArray:
foreach($secondArray as $key => $value) {
$firstArray[$key]['stockQT'] = $value;
}

PHP - Unexpected array_merge_recursive() output

I have this code
$a1 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
1 =>
array(1, 2, 3, 4, 5)
)
)
)
);
$a2 = array(
'success' => TRUE,
'data' => array(
'foo' =>
array(
21 =>
array(
7 =>
array(6, 7, 8, 9, 10)
)
)
)
);
$results = array();
$results = array_merge_recursive($results, $a1['data']);
$results = array_merge_recursive($results, $a2['data']);
var_dump($results);
From what I understood of array_merge_recursive(), I am expecting the results would be
array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
7 =>
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10
Instead I get this
array
'foo' =>
array
21 =>
array
1 =>
array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
22 =>
array
7 =>
array
0 => int 6
1 => int 7
2 => int 8
3 => int 9
4 => int 10
Where did the 22 index come from? Why is it outputting differently? Did I use the function wrong?
array_merge_recursive merges elements/arrays from the same depth as the first array, but if both arrays the key is a numerical index and they are the same it then appends to it. This is what is happening in your situation. since then your array is appended at 2nd level where index 21 is found by creating index 22. To receive the desired output you have change your index 21 to a string key like "x21"
Notes from php manual
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
I just came across the same issue, I wanted to merge the arrays but surprisingly found the keys were changed automatically in the result. The reason was because my "keys" are string of decimal numbers, without any alphabetic characters.
But luckily I noticed that if the keys have alphabetic characters, they could be reserved. So just came up with the following idea, which would append a letter 'S' to each key recursively before the merge, and later remove it in the final result.
Please refer to the enhanced_array_merge_recursive function for details:
<?php
$aa = [
'10' => 'book',
'14' => ['cat'],
];
$ab = [
'12' => 'cd',
'18' => 'cup',
'14' => ['dog'],
];
var_dump(enhanced_array_merge_recursive($aa, $ab));
function revise_keys($source)
{
if (!is_array($source)) {
return $source;
}
$target = [];
foreach ($source as $key => $value) {
$target['S' . $key] = revise_keys($value);
}
return $target;
}
function revert_keys($source)
{
if (!is_array($source)) {
return $source;
}
$target = [];
foreach ($source as $key => $value) {
$target[substr($key, 1 - strlen($key))] = revert_keys($value);
}
return $target;
}
function enhanced_array_merge_recursive(...$candidates)
{
$merged = [];
foreach ($candidates as $candidate) {
if (!is_array($candidate)) {
continue;
}
$merged = array_merge_recursive($merged, revise_keys($candidate));
}
return revert_keys($merged);
}
Output looks like following:
array(4) {
[10] =>
string(4) "book"
[14] =>
array(1) {
[0] =>
array(2) {
[0] =>
string(3) "cat"
[1] =>
string(3) "dog"
}
}
[12] =>
string(2) "cd"
[18] =>
string(3) "cup"
}

Combine Multiple Arrays - based on number?

It seems easy, but can't figure out how to do this. The current array data is listed by date and amount by date, so I need to combine all the dates: day, month, 6 month, 1 year. I need to arrange the array data to look like the second array below.
array
0 => enter code here
array
'1_day' => int 37
1 =>
array
'30_day' => int 3275
2 =>
array
'180_day' => int 3908
3 =>
array
'1_year' => int 6933
4 =>
array
'date' => string '2013-02-13' (length=10)
5 =>
array
'1_day' => int 46
6 =>
array
'30_day' => int 3134
7 =>
array
'180_day' => int 3764
8 =>
array
'1_year' => int 6820
9 =>
array
'date' => string '2013-02-12' (length=10)
10 =>
array
'1_day' => int 61
11 =>
array
'30_day' => int 3127
12 =>
array
'180_day' => int 3750
13 =>
array
'1_year' => int 6807
14 =>
array
'date' => string '2013-02-11' (length=10)
array
0 =>
'1_day' => int 37
'30_day' => int 3275
'180_day' => int 3908
'1_year' => int 6933
'date' => string '2013-02-13' (length=10)
1 =>
'1_day' => int 46
'30_day' => int 3134
'180_day' => int 3764
'1_year' => int 6820
'date' => string '2013-02-12' (length=10)
2 =>
'1_day' => int 61
'30_day' => int 3127
'180_day' => int 3750
'1_year' => int 6807
'date' => string '2013-02-11' (length=10)
Untested, but this should get you close:
<?php
$result = array();
for ($i = 0; $i <= count($array); $i++)
{
if ($array[$i] == 'date')
{
$result[] = array(
'1_day' => $array[$i-4],
'30_day' => $array[$i-3],
'180_day' => $array[$i-2],
'1_year' => $array[$i-1],
'date' => $array[$i],
);
}
}
Try this one....
$result = array();
$i = 0;
foreach($data as $key => $d)
{
$result[$i]['1_day'] = $data[$key]['1_day'];
$result[$i]['30_day'] = $data[$key+1]['30_day'];
$result[$i]['180_day'] = $data[$key+2]['180_day'];
$result[$i]['1_year'] = $data[$key+3]['1_year'];
$result[$i]['date'] = $data[$key+4]['date'];
$key = $key+5;
$i++;
}
Another approach:
<?php
$count = count($inArray);
//In place subarray merger, by this you don't have to modify keys every time they change.
//Constraint: A sub-array at every index.
for ($idx =0, $jdx =0; $idx < $count; $idx +=5, $jdx++) {
$inArray[$jdx] = array_merge($inArray[$idx],
$inArray[$idx +1],
$inArray[$idx +2],
$inArray[$idx +3],
$inArray[$idx +4]);
}
array_splice ($inArray, $count/5);
/* OR into another array */
for ($idx =0, $jdx =0; $idx < $count; $idx +=5, $jdx++) {
$newArray[$jdx] = array_merge($inArray[$idx],
$inArray[$idx +1],
$inArray[$idx +2],
$inArray[$idx +3],
$inArray[$idx +4]);
}
?>

Categories