Merge arrays made in a loop PHP - php

I have a array that, 3 repeats from the same week, but 3 differents users that have your totals separately:
array
0 =>
array
'week' => '1'
'user' => 'Oswaldo Aranha'
'totals' => 'value'
1 =>
array
'week' => '1'
'user' => 'Protogenes'
'totals' => 'value'
2 =>
array
'week' => '1'
'user' => 'Rego Barros'
'totals' => 'value'
3 =>
array
'week' => '2'
'user' => 'Oswaldo Aranha'
'totals' => 'value'
4 =>
array
'week' => '2'
'user' => 'Protogenes'
'totals' => 'value'
5 =>
array
'week' => '2'
'user' => 'Rego Barros'
'totals' => 'value'
...
I wanna to unify the week in one array, with the 3 users and your totals. Like this:
array
0 =>
array
'week' => '1'
'Oswaldo Aranha' => 'value'
'Protogenes' => 'value'
'Rego Barros' => 'value'
1 =>
array
'week' => '2'
'Oswaldo Aranha' => 'value'
'Protogenes' => 'value'
'Rego Barros' => 'value'
2 =>
array
'week' => '3'
'Oswaldo Aranha' => 'value'
'Protogenes' => 'value'
'Rego Barros' => 'value'
...
I'm trying using array_merge(), array_combine(), array_whatever() but doesn' work. How i do that?

you can use array_merge();
$arr=array_merge ( $array[0],$array[1] ,$array[3]);
i hope this will help you :)
for extra info this link will help you :
http://php.net/manual/en/function.array-merge.php

$array = [
[
'week' => '1',
'user' => 'Oswaldo Aranha',
'totals' => 'value'
],
[
'week' => '1',
'user' => 'Protogenes',
'totals' => 'value'
],
[
'week' => '1',
'user' => 'Rego Barros',
'totals' => 'value'
],
[
'week' => '2',
'user' => 'Oswaldo Aranha',
'totals' => 'value',
],
[
'week' => '2',
'user' => 'Protogenes',
'totals' => 'value'
]
];
function combineWeeks($array) {
$results = [];
for($i = 0;$i < count($array);$i++) {
$results[$array[$i]['week']][$array[$i]['user']] = $array[$i]['totals'];
$results[$array[$i]['week']]['week'] = $array[$i]['week'];
}
$combined = [];
foreach($results as $key => $value) {
$combined[] = $results[$key];
}
return $combined;
}
Usage:
$combinedArray = combineWeeks($array);
print_r($combinedArray);
output:
Array
(
[0] => Array
(
[Oswaldo Aranha] => value
[week] => 1
[Protogenes] => value
[Rego Barros] => value
)
[1] => Array
(
[Oswaldo Aranha] => value
[week] => 2
[Protogenes] => value
)
)

I think there is no php-function doing it for you. Just do it your own:
$in = $array;
$out = [];
foreach ($in as $curIn) {
if ( ! isset ($out[$curIn["week"]])) {
$out[$curIn["week"]] = [];
}
$out[$curIn["week"]][$curIn["user"]] = $curIn["totals"];
}
That's it.

Related

Loop Through Nested JSON Response PHP

I'm trying to loop through and return data ('rank' from 'rank_details') from a returned JSON response.
Here is a snippet of the JSON response (what I'm getting from: $array = json_decode($apiResponse); )
(object) array(
'obj' =>
array (
0 =>
(object) array(
'name' => 'I\'m a HellRazor (feat. Crucifix)',
'id' => 13859011,
'data' =>
array (
0 =>
(object) array(
'timestp' => '2019-10-27T00:00:00.000Z',
'score' => 1.9610844011276853,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 191,
'country' => 'RU',
'score' => 1.9610844011276853,
'genre' => 'Country',
),
),
),
1 =>
(object) array(
'timestp' => '2019-12-04T00:00:00.000Z',
'score' => 14.70808550760029,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 9,
'country' => 'CH',
'score' => 14.70808550760029,
'genre' => 'Country',
),
),
),
2 =>
(object) array(
'timestp' => '2020-03-18T00:00:00.000Z',
'score' => 13.299189761918104,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 5,
'country' => 'RU',
'score' => 13.299189761918104,
'genre' => 'Country',
),
),
),
3 =>
(object) array(
'timestp' => '2020-07-12T00:00:00.000Z',
'score' => 19.02841337415393,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 77,
'country' => 'DE',
'score' => 19.02841337415393,
'genre' => 'Country',
),
),
),
4 =>
(object) array(
'timestp' => '2020-10-02T00:00:00.000Z',
'score' => 2.631257456412845,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 154,
'country' => 'RU',
'score' => 2.631257456412845,
'genre' => 'Country',
),
),
),
5 =>
(object) array(
'timestp' => '2020-10-03T00:00:00.000Z',
'score' => 1.896575572629275,
'rank_details' =>
array (
0 =>
(object) array(
'rank' => 195,
'country' => 'RU',
'score' => 1.896575572629275,
'genre' => 'Country',
),
),
),
),
),.....
Here is a snippet of my code:
$apiResponse = curl_exec($cc);
$array = json_decode($apiResponse);
foreach ($array as $key => $arrays) { // This will search in the 2 jsons
foreach($arrays as $key => $value) {
echo "\n Record ID: " . $value->id;
echo "\n Record Name: " . $value->name;
echo "\n Record Rank: " . $value->obj->data->rank_details->rank;
echo "\n";
}
}
Record Name and ID come over fine, but anything not in the "top level" isn't coming over. Any help is GREATLY appreciated.
You have to index into the data and rank_details arrays even if there's only one entry.
This worked for me:
echo "\n Record Rank: " . $value->data[0]->rank_details[0]->rank;

Add values from multidimensional array to another array

Hello good morning wherever you are :D, i have a lil problem, i have this code of arrays
$arrayToView is the info of every single user that i want.
$tagsArray are only tags that use every user but i need to merge all the info something like the last array...
$arrayToView = array(
'IVOFACUNDO' = array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23
),
'ESRAYCU' = array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44
)
)
And i have another one like this
$tagsArray= array(
'IVOFACUNDO' = array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
),
'ESRAYCU' = array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
)
so the question is how i can merge both arrays obviously respectively with the same admin something like this
$arrayToView = array(
'IVOFACUNDO' = array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23,
'tags' => array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
),
'ESRAYCU' = array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44,
'tags' => array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
)
)
The key 'tags' need to be created in the merge of every iteration to add and get one array with all the values, how i can do this?
You can try this snippet.
foreach($arrayToView as $key => $arr){
if(array_key_exists($key, $tagsArray)){
$arrayToView[$key]['tags'] = $tagsArray[$key];
}
}
echo '<pre>';print_r($arrayToView);echo '</pre>';
Use php inbuilt function
$result_Arr = array_merge_recursive($arrayToView,$tagsArray);
<?php
$arrayToView = array(
'IVOFACUNDO' => array(
'mails' => 3,
'contacts' => 34,
'blocked' => 23
),
'ESRAYCU' => array(
'mails' => 23,
'contacts' => 124,
'blocked' => 44
)
);
$tagsArray= array(
'IVOFACUNDO' => array(
'14' => array(
'id' => 14,
'name' => 'php',
'value' => 1
),
'15' => array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
),
'ESRAYCU' => array(
'1' => array(
'id' => 1,
'name' => 'python',
'value' => 1
),
'15'=> array(
'id' => 15,
'name' => 'javascript',
'value' => 1
)
)
);
foreach($arrayToView as $key => $value){
if(isset($tagsArray[$key])){
$arrayToView[$key]['tags'] = array();
foreach($tagsArray[$key] as $key2 => $value2){
$arrayToView[$key]['tags'][$key2] = $tagsArray[$key][$key2];
}
}
}
echo'<pre>';
print_r($arrayToView);
echo'</pre>';
?>

Sort multidimentional array PHP by ids

Im trying to sort an multidimentional array based on a array in the order i would like it to appear in.
the $lookingfor array contains the order i would like it to appear, while $avaliableArray contains the whole multidimentional array. Would like the result in the example code called $resultarray
How would i do this, based on the id of the elements in $avaliableArray ?
code:
$avaliableArray = array(
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);
$lookingFor = array(1,8,4);
looking for result:
$resultArray = array(
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4")
);
Use usort() and apply proper id to $lookingFor same as array value.
$avaliableArray = array(
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-1"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-4"),
array('name' => 'Banken', 'site' => 'bank', 'avaliable' => true, 'type' => 'site', 'id' => "testid-8")
);
$lookingFor = array("testid-1","testid-8","testid-4");
usort($avaliableArray, function ($a, $b) use ($lookingFor) {
$pos_a = array_search($a['id'], $lookingFor);
$pos_b = array_search($b['id'], $lookingFor);
return $pos_a - $pos_b;
});
echo "<pre>";
print_r($avaliableArray);
Output
Array
(
[0] => Array
(
[name] => Banken
[site] => bank
[avaliable] => 1
[type] => site
[id] => testid-1
)
[1] => Array
(
[name] => Banken
[site] => bank
[avaliable] => 1
[type] => site
[id] => testid-8
)
[2] => Array
(
[name] => Banken
[site] => bank
[avaliable] => 1
[type] => site
[id] => testid-4
)
)
You should try usort :
function sortIt($a, $b) {
return strcasecmp($a['id'],$b['id']);
}
usort($resultArray, 'sortIt');
Try this:
function sortArr($a, $b) {
return intval(preg_replace('/[^0-9]+/', '', $a['id']), 10) - intval(preg_replace('/[^0-9]+/', '', $b['id']), 10) ; // it will extract number from string and compare it
}
usort($avaliableArray, 'sortArr');

Extracting data from complicated associative array in php and put into new array

I have an complicated array that looks like this:
$input=array(
(int) 0 => array(
'XXX' => array(
'id' => '7',
'p_id' => '1',
'address' => '9463',
'arrival_time' => '2014-05-01 03:30:00'
),
'YYY' => array(
'id' => '1',
'iden' => '1111',
'name' => 'Tom'
)
),
(int) 1 => array(
'XXX' => array(
'id' => '9',
'p_id' => '2',
'address' => '9469',
'arrival_time' => '2014-05-27 16:43:58'
),
'YYY' => array(
'id' => '2',
'iden' => '2222',
'name' => 'Sam'
)
),
(int) 2 => array(
'XXX' => array(
'id' => '3',
'p_id' => '3',
'address' => '9462',
'arrival_time' => '2014-04-21 14:05:00'
),
'YYY' => array(
'id' => '3',
'iden' => '3333',
'name' => 'James'
)
)
)
I would like to convert it such that it looks like this;
$output=array(
(int) 0 => array(
'name' => 'Tom',
'iden' => '1111',
'address' => '9463'
),
(int) 1 => array(
'name' => 'Sam',
'iden' => '2222',
'address' => '9469'
),
(int) 2 => array(
'name' => 'James',
'iden' => '3333',
'address' => '9462'
)
I wrote some code to solve this problem:
foreach ( $input as $key => $value)
{
$output['name']=$input[$key]['YYY']['name'];
$output['iden']=$input[$key]['YYY']['iden'];
$output['address']=$input[$key]['XXX']['address'];
}
Unfortunately, it retrieves only the last element of the input array.
Can someone more experienced help?
Thank you very much.
You are overwriting the values in each iteration, as you always write to $output['name'] etc.
foreach ( $input as $key => $value)
{
$output[$key] = array(
'name' => $value['YYY']['name'],
'iden' => $value['YYY']['iden'],
'address' => $value['XXX']['address']
);
}
The key here is using $output[$key] instead of $output - this way you will add a new element in each iteration.
Also $input[$key] and $value are equivalent, so I used the shorter variant ;)
Try this in your foreach loop :-
foreach ( $input as $key=>$value)
{
$output[$key]['name']=$value['YYY']['name'];
$output[$key]['iden']=$value['YYY']['iden'];
$output[$key]['address']=$value['XXX']['address'];
}
You have to add an index to the array in the foreach: $output[$key]["name"] = ...;

how to build an array in parent and child manner by fetching mysql data using php

this is my code where i am fetching my mysql record.
$parentChildArr=array();
//mysql query for fetching parent and child record
$selectparentMenu=mysql_query("SELECT `id`,`item_name`,`menu_type`,`parent` FROM `epic_master_menu`");
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[]=$fetchparentMenu['id'];
$parentChildArr[]=$fetchparentMenu['item_name'];
$parentChildArr[]=$fetchparentMenu['menu_type'];
$parentChildArr[]=$fetchparentMenu['parent'];
}
var_export($parentChildArr); // exporting or printing arrays
// when i export the array i get this output.
array ( 0 => '1', 1 => 'Dashboard', 2 => 'item', 3 => '0',
4 => '2', 5 => 'Admission', 6 => 'item', 7 => '0', 8 => '3',
9 => 'Examination', 10 => 'item', 11 => '0', 12 => '4',
13 => 'CET', 14 => 'item', 15 => '0');
but the problem is that i want to build the array like this.
$newarr=array ( 'dataSource' => array ( 0 => array ( 'id' => '1',
'text' => 'Dashboard', 'expanded' => 'true', 'spriteCssClass' => 'rootfolder',
'items' => array ( 0 => array ( 'id' => '89', 'text' => 'Users',
'expanded' => true, 'spriteCssClass' => 'folder',
'items' => array ( 0 => array ( 'id' => '94', 'text' => 'Users',
'spriteCssClass' => 'html', ), 1 => array ( 'id' => '94',
'text' => 'Users', 'spriteCssClass' => 'html', ), 2 => array (
'id' => '94', 'text' => 'Users', 'spriteCssClass' => 'image' ) ) ) ) ) ));
database table view is...
i am not getting the logic that how to build the array like $newarr. thank you
not tested, but you need to defined a structure and then you need to go recursive... so you can check where is the parent entry to my child ...
function structure($data){
return array(
'id' => $data['id'],
'item_name' => $data['item_name'],
'menu_type' => $data['menu_type'],
'parent' => $data['parent'],
'expanded' => false,
'childs' => array()
);
}
function recursiveImport(&$parent, $data){
foreach($parent AS $key => $value){
if($value['id'] == $data['parent']){
$parent[$key]['childs'][] = structure($data);
$parent[$key]['expanded'] = true;
return true;
}
else{
if(count($value['childs']) > 0){
foreach($value['childs'] AS $key2 => $child){
$result = recursiveImport($parent[$key]['childs'][$key2], $data);
if($result === true) return true;
}
}
}
}
return false;
}
$newarr = array();
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$result = recursiveImport($newarr , $fetchparentMenu);
if($result === false){
$newarr[] = structure($fetchparentMenu);
}
}
//output array
array ( 0 => array ( 'id' => '1', 'item_name' => 'Dashboard', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 1 => array ( 'id' => '2', 'item_name' => 'Admission', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 2 => array ( 'id' => '3', 'item_name' => 'Examination', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 3 => array ( 'id' => '4', 'item_name' => 'CET', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), )
Use following code
$m=0;
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[$m][]=$fetchparentMenu['id'];
$parentChildArr[$m][]=$fetchparentMenu['item_name'];
$parentChildArr[$m][]=$fetchparentMenu['menu_type'];
$parentChildArr[$m][]=$fetchparentMenu['parent'];
$m++;
}

Categories