Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);
Related
I have an array($data) like this.
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.80
[TOPUP_AMOUNT] => 58000.00
[TOTAL_EXPENSES] => 3114.41
)
.....
I need to get a new key called TOTAL_BALANCE and it should get as follows,
TOTAL_BALANCE=JOINED_VALUE+TOPUP_AMOUNT+TOTAL_EXPENSES
Final output should look as follows,
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.80
[TOPUP_AMOUNT] => 58000.00
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 78119.39
)
.....
Can someone help me to achieve this?
Here is my try, but I am not sure this is correct or not.
$r = [];
$keys = array_keys($key1+$key2);
foreach($keys as $v){
??
}
Do it like this:
$data = Array(
0 => Array(
'PID' => 1,
'USER_NAME' => 'JOHN',
'JOINED_DATE' => '2022-01-31',
'JOINED_VALUE' => 23233.80,
'TOPUP_AMOUNT' => 58000.00,
'TOTAL_EXPENSES' => 3114.41,
),
1 => Array(
'PID' => 2,
'USER_NAME' => 'JOHN_2',
'JOINED_DATE' => '2022-01-31',
'JOINED_VALUE' => 1234.80,
'TOPUP_AMOUNT' => 1000.00,
'TOTAL_EXPENSES' => 3114.41,
)
);
foreach($data as &$value){
// Sum and store
$value['TOTAL_BALANCE'] = $value['JOINED_VALUE'] + $value['TOPUP_AMOUNT'] + $value['TOTAL_EXPENSES'];
}
print_r($data);
Output:
Array
(
[0] => Array
(
[PID] => 1
[USER_NAME] => JOHN
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 23233.8
[TOPUP_AMOUNT] => 58000
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 84348.21
)
[1] => Array
(
[PID] => 2
[USER_NAME] => JOHN_2
[JOINED_DATE] => 2022-01-31
[JOINED_VALUE] => 1234.8
[TOPUP_AMOUNT] => 1000
[TOTAL_EXPENSES] => 3114.41
[TOTAL_BALANCE] => 5349.21
)
)
I have tried using this example here Return index of highest value in an array
But that does not go into a multi dimensional Array
I have tried ARRAY_COLUMN(), array_values(), array_shift, Max and Min but they are not getting the info i need
I want to be able to loop thru and get to:
[pricing]
then Check pricing to see which is the highest and lowest in the nested array
so like below which total was the Highest and lowest trades on these dates
[2017-09-22]
[2017-09-23]
obviously [2017-09-23] is a simple one, i just dint want to add much more code for ppl helping to go thru.
The Array i create looks like this:
Array
(
[2017-09-23] => Array
(
[0] => Array
(
[timestamp] => 1506169387000
[pricing] => 9.5470
[qty] => 25
[total] => 238.675
[date] => 2017-09-23
)
)
[2017-09-22] => Array
(
[0] => Array
(
[timestamp] => 1506093083000
[pricing] => 9.6300
[qty] => 25
[total] => 240.75
[date] => 2017-09-22
)
[1] => Array
(
[timestamp] => 1506077220000
[pricing] => 8.7190
[qty] => 13
[total] => 113.347
[date] => 2017-09-22
)
[2] => Array
(
[timestamp] => 1506077109000
[pricing] => 8.6800
[qty] => 83
[total] => 720.44
[date] => 2017-09-22
)
[3] => Array
(
[timestamp] => 1506065258000
[pricing] => 8.7100
[qty] => 25
[total] => 217.75
[date] => 2017-09-22
)
)
in the example above i would like it to Create a new array with only the following
date -> last timestamp -> Highest pricing -> Lowest lowest -> Total of all Totals -> first Timestamp
EDIT: the last and first Timestamp are basically the first and last index so in this case:
[timestamp] => 1506093083000 and [timestamp] => 1506065258000
or Index [0] and index [3]
The array from your question:
$array = array (
'2017-09-23' =>
array (
0 =>
array (
'timestamp' => '1506169387000',
'pricing' => '9.5470',
'qty' => '25',
'total' => '238.675',
'date' => '2017-09-23',
),
),
'2017-09-22' =>
array (
0 =>
array (
'timestamp' => '1506093083000',
'pricing' => '9.6300',
'qty' => '25',
'total' => '240.75',
'date' => '2017-09-22',
),
1 =>
array (
'timestamp' => '1506077220000',
'pricing' => '8.7190',
'qty' => '13',
'total' => '113.347',
'date' => '2017-09-22',
),
2 =>
array (
'timestamp' => '1506077109000',
'pricing' => '8.6800',
'qty' => '83',
'total' => '720.44',
'date' => '2017-09-22',
),
3 =>
array (
'timestamp' => '1506065258000',
'pricing' => '8.7100',
'qty' => '25',
'total' => '217.75',
'date' => '2017-09-22',
),
),
);
To get the values maybe you can use array_map and with this the function array_column is the key of all, try with this:
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => reset($timestamps),
'last_timestamp' => end($timestamps),
];
}, $array);
$values is an array with the filter values that you need:
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => 1506169387000
[last_timestamp] => 1506169387000
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => 1506093083000
[last_timestamp] => 1506065258000
)
)
EDIT
Get the pricing of the [first_timestamp] and [last_timestamp]
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => [
'value' => reset($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
],
'last_timestamp' => [
'value' => end($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
]
];
}, $array);
I added an array to both timestamps with the value of these and the pricing.
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
[last_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => Array
(
[value] => 1506093083000
[pricing] => 9.6300
)
[last_timestamp] => Array
(
[value] => 1506065258000
[pricing] => 8.7100
)
)
)
Hello I have this multi dimensional array which needs to be inserted to the database table.
so far I have come up with this solution which don't work fully. I have a form that support dynamic fields many dynamic fields. I want to save those dynamically created fields using this function. First I had been able to create a loop to format the data.
I used this loop to format the data
$url = str_replace(' ','-',strtolower($this->input->post('title')));
$data = ['business' => [
'title' => $this->input->post('title'),
'URL' => $url,
'category' => $this->input->post('category'),
'region' => $this->input->post('region')
],
'description_' => [
'text' => $this->input->post('description'),
],
'logo_' => [
'blob' => $this->input->post('logo'),
]];
$nyingi = [ 'location_' => ['text' => 'loc_txt','priority' => 'loc_order'],
'photo_' => ['path' => 'p_txt'],
'video_' => ['path' => 'v_txt'],
'product_' => ['p_id' => 'pt_q', 'text' => 'pt_txt', 'expire' => 'pt_xpr', 'title' => 'pt_tt'],
'service_' => ['p_id' => 'st_q', 'text' => 'st_txt', 'expire' => 'st_xpr', 'title' => 'st_tt'],
'hours_' => ['time1' => 't1', 'time2' => 't2', 'type' => 'tt'],
'map_' => ['text' => 'm_txt']
];
foreach($nyingi as $ins => $vl){
foreach($vl as $fld => $box){
$uwazi = $this->input->post($box);
if(is_array($uwazi) && 1<count($uwazi)){
foreach($uwazi as $bb){
$one[$ins][$fld][] = $bb;
}
} elseif(is_array($uwazi) && 1==count($uwazi)) {
print_r($uwazi);
}
}
}
for($g=0;$g<count($one);$g++){
for($h=0;$h<count($one[$g]);$h++){
for($z=0;$z<count($one[$g][$h]);$z++){
//if(array_key_exists($one[$g][$h+1], $one)){
print $one[$g][$h][$z+1];
//}
}
}
}
$data = array_merge($data, $one);
The output of the above code
[location_] => Array
(
[text] => Array
(
[0] => Lemara Main Office
[1] => Themi branch
[2] => Sinoni branch
)
[priority] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[photo_] => Array
(
[path] => Array
(
[0] => lemaraphoto.png
[1] => themiphoto.png
[2] => sinoniphoto.png
)
)
[video_] => Array
(
[path] => Array
(
[0] => lemaravideo.mp4
[1] => themivideo.mp4
[2] => sinonivideo.mp4
)
)
[product_] => Array
(
[p_id] => Array
(
[0] => product photo
[1] => product 3 photo
[2] => Product 2 photo
)
[text] => Array
(
[0] => product desc
[1] => product 3 desc
[2] => product 2 desc
)
[expire] => Array
(
[0] => product expire
[1] => product 3 expire
[2] => Product 2 expire
)
[title] => Array
(
[0] => product
[1] => Product 3
[2] => Product 2
)
)
[service_] => Array
(
[p_id] => Array
(
[0] => Service 2 photo
[1] => service 3 photo
[2] => service photo
)
[text] => Array
(
[0] => service 2 desc
[1] => service 3 desc
[2] => service desc
)
[expire] => Array
(
[0] => Service 2 expire
[1] => service 3 expire
[2] => service expire
)
[title] => Array
(
[0] => Service 2
[1] => service 3
[2] => service
)
)
)
I have this add_bz function
function add_bz($data){
$this->db->trans_start(); $er=0;
foreach($data as $table => $sql){
if($table==="business"){
$this->db->insert($table, $sql);
$id = $this->db->insert_id();
} else {
array_merge($sql, array('idd' => $id));
$this->db->insert($table, $sql);}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;}
return TRUE;
}
That function allows me to insert the data in this format only.
[[business] => Array
(
[title] => Email Marketing
[URL] => email-marketing
[category] => 3
[region] => 2
)
[description_] => Array
(
[text] => Some desc
)
[logo_] => Array
(
[blob] => mainlogo.png
)
]
as business, decription_, logo_ are db tables where title, URL, category, region, text, blob are the db columns to the corresponding tables and the rest is data that goes to those columns.
How I want it to works. For example in location_
I want to the array to change into my working format or something else that will work like this
location_ => ['text' => [[0] => 'Lemara Main Office'],
'priority' => [[0] => '1']
]
location_ => ['text' => [[1] => 'Themi Office'],
'priority' => [[1] => '2']
]
location_ => ['text' => [[2] => 'Sinoni Office'],
'priority' => [[2] => '3']
]
or like this
location_ => [0 => [['text' => 'Lemara Main Office'],
['priority' => '1']
],
1 => [['text' => 'Themi Main Office'],
['priority' => '2']
],
2 => [['text' => 'Sinoni Main Office'],
['priority' => '3']
]
],
And also support many columns not just the two.
Any help is deeply appreciated as I have been struggling for days to make this work. Thanks in advance.
I would suggest you convert your array to JSON String then insert it to DB as text.
JSON would handle your multidimentional data so well,
To convert your array to JSON : http://php.net/manual/en/function.json-encode.php
To convert your JSON to Array : http://php.net/manual/en/function.json-decode.php
My array is like that:
Array
(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
)
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
[2] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[3] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
I want to change that array like that depending on key['type']. If array key['type'] are same, I want to change array like that:
Array
(
[car] => Array(
[0]=>Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 1
[tran_name] => private
[tran_image] => 1251961905A1.jpg
[type] => car
[troute_id] => 10
),
[1] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 2
[tran_name] => express
[tran_image] => bus3.jpg
[type] => car
[troute_id] => 13
)
),
[train]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 3
[tran_name] => MyanmarTrain
[tran_image] => Burma-Gorteikviaduct.jpg
[type] => train
[troute_id] => 16
)
[cruise]=>Array(
[0] => Array
(
[des_id] => 1
[des_name] => bagan
[tran_id] => 4
[tran_name] => Ayeyarwaddy Cruise
[tran_image] => boat-ChutzpahToo1.jpg
[type] => cruise
[troute_id] => 22
)
)
)
)
what I mean is that if key['type'] is car, I want to create car array or if the type is train I want to create train array or if the type is cruise I want to create cruise array. I don't know how to loop the array. Anyone please help me. Thanks a lot!
Here's a simple way to do it: loop over the data, and just append to the subarray matching the type value:
// starting data
$starting_array = array (
0 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 1,
'tran_name' => 'private',
'tran_image' => '1251961905A1.jpg',
'type' => 'car',
'troute_id' => 10
),
1 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 2,
'tran_name' => 'express',
'tran_image' => 'bus3.jpg',
'type' => 'car',
'troute_id' => 13
),
2 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 3,
'tran_name' => 'MyanmarTrain',
'tran_image' => 'Burma-Gorteikviaduct.jpg',
'type' => 'train',
'troute_id' => 16
),
3 => array (
'des_id' => 1,
'des_name' => 'bagan',
'tran_id' => 4,
'tran_name' => 'Ayeyarwaddy Cruise',
'tran_image' => 'boat-ChutzpahToo1.jpg',
'type' => 'cruise',
'troute_id' => 22
)
);
// initialize the result array
$result = array();
// loop over the starting array
foreach($starting_array as $entry) {
// make sure the result array has a key matching this item's type
if(!array_key_exists($entry['type'], $result)) {
$result[ $entry['type'] ] = array();
}
// add this item to the result array
$result[ $entry['type'] ][] = $entry;
}
// this is just for testing, so you can verify the output matches your desired result
echo "<pre>";
var_dump($result);
echo "</pre>";
Try this:
<?php
$tempArr = Array
(
Array(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 1,
"tran_name" => "private",
"tran_image" => "1251961905A1.jpg",
"type" => "car",
"troute_id" => 10
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 2,
"tran_name" => "express",
"tran_image" => "bus3.jpg",
"type" => "car",
"troute_id" => 13
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 3,
"tran_name" => "MyanmarTrain",
"tran_image" => "Burma-Gorteikviaduct.jpg",
"type" => "train",
"troute_id" => 16
),
Array
(
"des_id" => 1,
"des_name" => "bagan",
"tran_id" => 4,
"tran_name" => "Ayeyarwaddy Cruise",
"tran_image" => "boat-ChutzpahToo1.jpg",
"type" => "cruise",
"troute_id" => 22
)
);
$resultArr = array();
foreach($tempArr as $tempKey=>$temp)
{
if(!array_key_exists($temp['type'], $resultArr))
{
$resultArr[$temp['type']] = array();
}
$resultArr[$temp['type']][] = $temp;
}
echo '<pre>';
print_r($resultArr);
?>
This is working fine .....
i've a similar array:
Array
(
[0] => Array
(
[id] => 1
[name] => Mario
[type] => Doctor
[operations] => brain
[balance] => 3.00
)
[1] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hearth
[balance] => 6.00
)
[2] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => hands
[balance] => 4.00
)
[3] => Array
(
[id] => 3
[name] => Luca
[type] => Doctor
[operations] => foots
[balance] => 1.00
)
)
I must to merge it for id, so obtain only 2 elements for array (0 and 1) and Luca (id 3) must be unified for operations, in a new array, similar to this, so in future print more clearly operations unified and not divided.
[...]
)
[1] => Array
(
[id] => 3
[name] => luca
[type] => doctore
[operations] => Array (6.00 hearts,
4.00 hands,
1.00 foots)
)
I can not figure how solve my trouble... Someone could help me please? Thank you very much to all!
<?php
$input = array(
array('id' => 1, 'name' => 'Mario', 'type' => 'Doctor', 'operations' => 'brain', 'balance' => 3.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hearth', 'balance' => 6.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'hands', 'balance' => 4.00),
array('id' => 3, 'name' => 'Luca', 'type' => 'Doctor', 'operations' => 'foots', 'balance' => 1.00),
);
$output = array();
foreach ($input as $person)
{
// Add the person to the output, if needed.
if (array_key_exists($person['id'], $output) === false)
{
$output[$person['id']] =
array(
'id' => $person['id'],
'name' => $person['name'],
'type' => $person['type'],
'operations' => array(),
);
}
// Add the operation to the array of operations.
$output[$person['id']]['operations'][] =
array(
'type' => $person['operations'],
'balance' => $person['balance'],
));
}
foreach ($output as $person)
{
if (count($person['operations']) === 1)
{
// If the array contains only 1 item, pull it out of the array.
$output[$person['id']]['operations'] = $person['operations'][0];
}
}
print_r($output);