Reorganizing a PHP array structure (arrays within arrays) - php

I have this array within array which contains a lot of values:
183 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-09' (length=10)
2 => string 'GK' (length=2)
184 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-08' (length=10)
2 => string 'GL' (length=2)
185 =>
array (size=3)
0 => string 'FR' (length=2)
1 => string '2015-06-09' (length=10)
2 => string 'GN' (length=2)
186 =>
array (size=3)
0 => string 'FR' (length=2)
1 => string '2015-09-08' (length=10)
2 => string 'GO' (length=2)
0 is the country code. 1 is a date. 2 is a column on an Excel file.
I want to organize it in this way:
2015-06-09 =>
array (size=3)
DE =>
array (size=2)
column => GK
download => 666
FR =>
array (size=2)
column => GN
download => 777
2015-06-08 =>
array (size=3)
DE =>
array (size=2)
column => GL
download => 666
FR =>
array (size=2)
column => GO
download => 777
So the same date can show up more than once. if it gets to an array value with the same date - it inserts in it the country code with and its' column.
if it has more than 1 country - it adds a new country. (with the 'download' and column values).
I have this function:
function get_cols_to_array_by_date($array) {
$mainarr = array();
$last_in_arr = count($array);
for ($i=0; $i<$last_in_arr; $i++){
$mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );
}
return $mainarr;
}
which outputs an array that runs over the country when it gets to the same date and doesn't give me an array of countries.
What part am I missing in my code?
Is there a simpler way to do it? ( PHP syntax shortcuts ;) )

Assuming that the downloads is the key of the initial array, and each element has 3 elements(date and 2 countries):
Code:
//demo array
$old = array(
555=>array(
0 => 'DE',
1 => '2015-06-09',
2 => 'GK'),
234=>array(
0 => 'DE',
1 => '2015-06-08',
2 => 'GL'),
123=>array(
0 => 'FR',
1 => '2015-06-09',
2 => 'GN')
);
$new = array();
foreach($old as $key=>$arrayValues)
{
if(!array_key_exists($arrayValues[1], $new)){ //check if there is already a key by date
$new[$arrayValues[1]] = array();
}
$new[$arrayValues[1]][$arrayValues[0]] = array('column'=>$arrayValues[2], 'downloads'=>$key); //append formated array
}
echo "<pre>";
var_dump($new);
echo "</pre>";
Output:
array(2) {
["2015-06-09"]=>
array(2) {
["DE"]=>
array(2) {
["column"]=>
string(2) "GK"
["downloads"]=>
int(555)
}
["FR"]=>
array(2) {
["column"]=>
string(2) "GN"
["downloads"]=>
int(123)
}
}
["2015-06-08"]=>
array(1) {
["DE"]=>
array(2) {
["column"]=>
string(2) "GL"
["downloads"]=>
int(234)
}
}
}

Try looping and checking if element exists, if not - add it.
$result = [];
foreach ($myArray as $key => $values) {
if (!isset($result[$values[1]])) {
$result[$values[1]] = [
$values[0] => [
'column' => $values[2],
'download' => $key,
]
];
} elseif (!isset($result[$values[1]][$values[0]])) {
$result[$values[1]][$values[0]] = [
'column' => $values[2],
'download' => $key,
];
}
}
Sandbox

Related

Modifying one dimenstional array into two dimensional array php

I have a single-dimensional array $rec = ['123','456','789'] that I would like to modify into an array like:
array(
'id' => 0,
'addr' => 123,
),
array(
'id' => 0,
'addr' => 456,
),
array(
'id' => 0,
'addr' => 789,
),
To achieve that I have tried looping the original array and inserting each row into the new array like:
$rec = ['123','456','789']
$newList = [];
foreach($rec as $i => $r){
$row = array(
'id' => $i,
'addr' => $r,
);
$newList = array_combine($newList,$row);
}
return $newList;
This results in
{
"id": 2,
"addr": "789"
}
How do I go about to get what I want?
You cannot use array_combine for this purpose
$rec = ['123','456','789'];
$newList = [];
foreach($rec as $i => $r){
$newList[] = array(
'id' => 0,
'addr' => $r,
);
}
var_dump($newList) ;
var_dump Result will be
array(3) {
[0]=>
array(2) {
["id"]=>
int(0)
["addr"]=>
string(3) "123"
}
[1]=>
array(2) {
["id"]=>
int(0)
["addr"]=>
string(3) "456"
}
[2]=>
array(2) {
["id"]=>
int(0)
["addr"]=>
string(3) "789"
}
}
echo json_encode($newList) ;
[
{
"id": 0,
"addr": "123"
},
{
"id": 0,
"addr": "456"
},
{
"id": 0,
"addr": "789"
}
]
$rec = ['123','456','789'];
$newArray = [];
foreach($rec as $item) {
$newArray[] = [
'id' => 0, // or whatever number you want here
'addr' => $item,
];
}
var_dump($newArray);
Result:
//array (size=3)
// 0 =>
// array (size=2)
// 'id' => int 0
// 'addr' => string '123' (length=3)
// 1 =>
// array (size=2)
// 'id' => int 0
// 'addr' => string '456' (length=3)
// 2 =>
// array (size=2)
// 'id' => int 0
// 'addr' => string '789' (length=3)
This can also be done using a for loop(or any other sort of loop for that matter).
Using your original idea, we can also achive that:
$rec = ['123','456','789'];
$newList = [];
foreach($rec as $i => $r){
$row = array(
'id' => $i,
'addr' => $r,
);
$newList[] = array_combine(array_keys($row), array_values($row));
}
var_dump($newList);
Result:
array (size=3)
0 =>
array (size=2)
'id' => int 0
'addr' => string '123' (length=3)
1 =>
array (size=2)
'id' => int 1
'addr' => string '456' (length=3)
2 =>
array (size=2)
'id' => int 2
'addr' => string '789' (length=3)
Lets take a look at what array_combine does
/**
* Creates an array by using one array for keys and another for its values
* #link https://php.net/manual/en/function.array-combine.php
* #param array $keys <p>
* Array of keys to be used. Illegal values for key will be
* converted to string.
* </p>
* #param array $values <p>
* Array of values to be used
* </p>
* #return array|false the combined array, false if the number of elements
* for each array isn't equal or if the arrays are empty.
* #meta
*/
#[Pure]
function array_combine(array $keys, array $values) { }
So you would infact need to get array_keys and array_values from the $row array, also add the new array to the original using []. Which is very redundant.
try this
$rec = ['123','456','789'];
array_walk($rec, function($value,&$startNum ) use(&$result){
$result[]=['id'=>$startNum ++,'addr'=>$value];
},);
print_r($result);
Output
Array (
[0] => Array ( [id] => 0 [addr] => 123 )
[1] => Array ( [id] => 1 [addr] => 456 )
[2] => Array ( [id] => 2 [addr] => 789 ) )

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;
}

slice and merge 2 arrays

is there a good way to slice and merge 2 arrays based on empty values for example
first array
0 => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
1 => string '' (length=0)
2 => string '' (length=0)
3 => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
4 => string '' (length=0)
5 => string '' (length=0)
second array
0 => string '' (length=0)
1 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
2 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
3 => string '' (length=0)
4 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
5 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)
I want them to be like this array
array (size=2)
0 =>
array (size=2)
'comment' => string 'Perfect all gorgeous and arrived in less than 1 month for brazil' (length=64)
'images' =>
array (size=2)
0 => string 'http://g01.a.alicdn.com/kf/UTB8jjnecFfFXKJk43Otq6xIPFXaw.jpg" data-eid="eid-201782563197' (length=88)
1 => string 'http://g01.a.alicdn.com/kf/UTB87.bdcNHEXKJk43Jeq6yeeXXaZ.jpg" data-eid="eid-201782563197' (length=88)
1 =>
array (size=2)
'comment' => string 'Good figures for their money, only instead of bits normal stick child bit rastroilsya' (length=85)
'images' =>
array (size=2)
3 => string 'http://g01.a.alicdn.com/kf/UTB8cxXwg4HEXKJk43Jeq6yeeXXam.jpg" data-eid="eid-201833045441' (length=88)
4 => string 'http://g04.a.alicdn.com/kf/UTB824Xwg4HEXKJk43Jeq6yeeXXaB.jpg" data-eid="eid-201833045441' (length=88)
How to do it ?
Got something that will help. It will work with more inputs if you need. It might not work best if your second array has more than one breaking blank. Just working on updated code to solve such issues.
<?php
$arr1 = array("input", "", "", "another input", "", "", "yet another input", "");
$arr2 = array("", "p1", "p2", "", "p01", "p02", "","p11" );
$inp = array("comment" => $arr1, "images" => $arr2);
function mangle_arrays($input) {
$out = array();
$gen = 0;
foreach($input as $key=>$val) {
$id = $gen?-1:0;
if ($gen) {
foreach($val as $v) {
if ($v) {
$out[$id][$key][] = $v;
} else {
$id++;
}
}
} else {
foreach($val as $v) {
if ($v) {
$out[$id] = array();
$out[$id][$key] = $v;
$id++;
}
}
}
$gen++;
}
return $out;
}
// your code goes here
echo "<pre>";
print_r(mangle_arrays($inp));
Results
Array
(
[0] => Array
(
[comment] => input
[images] => Array
(
[0] => p1
[1] => p2
)
)
[1] => Array
(
[comment] => another input
[images] => Array
(
[0] => p01
[1] => p02
)
)
[2] => Array
(
[comment] => yet another input
[images] => Array
(
[0] => p11
)
)
)

PHP How to sum values of the array of the same key

This Question might seem duplicate, but I swear to have tried and tried thousands of solutions for many hours now...
I have got an associative multidimentional array like this:
1 =>
array (size=1)
'Pld' =>
array (size=2)
'score_good_answers' => string '1' (length=1)
'score_bad_answers' => string '0' (length=1)
2 =>
array (size=1)
'Aln' =>
array (size=2)
'score_good_answers' => string '0' (length=1)
'score_bad_answers' => string '1' (length=1)
3=>
array (size=1)
'IPS' =>
array (size=2)
'score_good_answers' => string '1' (length=1)
'score_bad_answers' => string '0' (length=1)
4 =>
array (size=1)
'Pld' =>
array (size=2)
'score_good_answers' => string '1' (length=1)
'score_bad_answers' => string '0' (length=1)
5 =>
array (size=1)
'Aln' =>
array (size=2)
'score_good_answers' => string '1' (length=1)
'score_bad_answers' => string '0' (length=1)
6 =>
array (size=1)
'Aln' =>
array (size=2)
'score_good_answers' => string '1' (length=1)
'score_bad_answers' => string '0' (length=1)
FOR Var_Export:
1=> array ( 'Pld' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 2 => array ( 'Aln' => array ( 'score_good_answers' => '0', 'score_bad_answers' => '1', ), ), 3 => array ( 'IPS' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 4 => array ( 'Pld' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 5 => array ( 'Aln' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ), 6 => array ( 'Aln' => array ( 'score_good_answers' => '1', 'score_bad_answers' => '0', ), ),
I need to SUM the all the 'score_good_answers' and the 'score_bad_answers' for all Alns and Plds and so forth.
The Worse case scenario is that, this keys i.e: are changeable values.
At this level, whatever solution that works will be well appreciated.
I tried the Accepted Answer in this SO Question: How to sum values of the array of the same key?
However, It seems to throw several Errors....
And I Tried Several More Solutions from several SO Questions,
i.e: How to sum values of the array of the same key?, Array sum of value based on same key, How to sum values via the same key and group by other key and many more...
An other close one was this:How to sum same array in php
And tried:
$array2 = array();
for($f = 0; $f<count($getCategories); $f++){
foreach($getCategories[$i] as $k=>$v) {
if(!isset($array2[$v['Aln']])) {
$array2[$v['Aln']] = $v;
} else {
$array2[$v['Aln']]['score_good_answers'] += $v['score_good_answers'];
}
}
} var_dump($array2);
I still get Several Errors including invalid arguments undefined offsets and many more
Humbly request for any suggestion.
Thank you very much
You can use this code:
$answers = array();
foreach ($getCategories as $categories){
foreach($categories as $category => $scores){
foreach ($scores as $type => $score){
if (isset($answers[$category][$type])){
$answers[$category][$type] += (int) $score;
} else {
$answers[$category][$type] = (int) $score;
}
}
}
}
The output of will be the following array:
Array
(
[Pld] => Array
(
[score_good_answers] => 2
[score_bad_answers] => 0
)
[Aln] => Array
(
[score_good_answers] => 2
[score_bad_answers] => 1
)
[IPS] => Array
(
[score_good_answers] => 1
[score_bad_answers] => 0
)
)
The variable that holds the key is named $f, but you try to use the undefined variable $i on the next line, see? That is one of your warnings and will not do what you want it to. Use $f on the second line.
for($f = 0; $f<count($getCategories); $f++){
foreach($getCategories[$i] as $k=>$v) {
Your data structure seems a bit odd? Is there always just one key in the second top-most array?
This would be prettier if possible:
array(2) {
[0] => stdClass#1 (3) {
public $name => string(4) "Pld"
public $score_good_answers => int(1)
public $score_bad_answers=> int(0)
}
[1] => stdClass#1 (3) {
public $name => string(4) "Aln"
public $score_good_answers => int(0)
public $score_bad_answers=> int(1)
}
}
I can not see what end result you want, but give this a try, might not fit what you want though.
$goodAnswersByCategoryDataKey = array();
$badAnswersByCategoryDataKey = array();
foreach ($categories as $i => $category) {
foreach ($category as $categoryDataKey => $categoryData) {
if (!isset($goodAnswersByCategoryDataKey[$categoryDataKey])) {
$goodAnswersByCategoryDataKey[$categoryDataKey] = 0;
}
$goodAnswersByCategoryDataKey[categoryDataKey] += $categoryData['score_good_answers'];
if (!isset($badAnswersByCategoryDataKey[$categoryDataKey])) {
$badAnswersByCategoryDataKey[$categoryDataKey] = 0;
}
$badAnswersByCategoryDataKey[$categoryDataKey] += $categoryData['score_bad_answers'];
}
}
var_dump(goodAnswersByCategoryDataKey);
var_dump(badAnswersByCategoryDataKey);
If it's an iterative structure like in your example you can do this :
$answers = [];
$nbCat = count($getCategories);
for($i = 0; $i < $nbCat; $i++) {
foreach($getCategories[$i] as $key => $scores) {
if(empty($answers[$key])) {
$answers[$key] = $scores;
}
else {
$answers[$key]['score_good_answers'] += $scores['score_good_answers'];
$answers[$key]['score_bad_answers'] += $scores['score_bad_answers'];
}
}
}

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"
}

Categories