I have an array:
Array
(
[0] => Array
(
[id] => 81
[placed] => 2013-09-19 16:32:53
[sub_total] => 786
)
[1] => Array
(
[id] => 80
[placed] => 2013-09-19 16:32:06
[sub_total] => 780
)
[2] => Array
(
[id] => 79
[placed] => 2013-09-18 17:06:48
[sub_total] => 786
)
[3] => Array
(
[id] => 78
[placed] => 2013-09-18 17:05:02
[sub_total] => 756
)
[4] => Array
(
[id] => 77
[placed] => 2013-09-17 17:02:53
[sub_total] => 786
)
[5] => Array
(
[id] => 76
[placed] => 2013-09-16 17:02:53
[sub_total] => 756
)
)
Is it possible to group this data by date and summarize subtotal amount to get output array:
Array
(
[0] => Array
(
[placed] => 2013-09-19
[sub_total] => 786 + 780
)
[2] => Array
(
[placed] => 2013-09-18
[sub_total] => 786 + 756
)
[3] => Array
(
[placed] => 2013-09-17 17:02:53
[sub_total] => 786
)
[4] => Array
(
[placed] => 2013-09-16 17:02:53
[sub_total] => 756
)
)
$output=array();
foreach($yourArray as $values)
{
$d=date("Y-m-d",strtotime($values["placed"]));
$output[$d]["sub_total"]+=$values["sub_total"];
}
print_r($output);
Fiddle
Credits: The initial array used on this fiddle was taken from the answer by Jason OOO below.
I tested this also: http://phpfiddle.org/main/code/rzv-ngp
<?php
Array
(
'0' => Array
(
'id' => '81',
'placed' => '2013-09-19 16:32:53',
'sub_total' => '786'
),
'1' => Array
(
'id' => '80',
'placed' => '2013-09-19 16:32:06',
'sub_total' => '780'
),
//...
);
$newarray = array();
foreach ($array as $value){
$temp = explode(" ", $value['placed']);
$date = $temp[0];
$total = (isset($newarray[$date]['sub_total']) ? $newarray[$date]['sub_total'] + $value['sub_total']: $value['sub_total']);
$newarray[$date] = array('placed' => $date, 'sub_total' => $total);
}
print_r($newarray);
?>
You can have that kind of array at querying time. Something like
select date_field_name,other_field from table_name group by Day(date_feild_name);
after that you can use a use foreach to work with each day's data!
Try using sub query
select field_name,DAY(date_field) as date,(select sum(sub_total) where DAY(date_field)=date) as sub_total from table_name group by day(date_field)
Try this code
<?php
$shop = array(array( id => '81',
placed => '2013-09-19',
sub_total => '786'
),
array( id =>'80',
placed => '2013-09-19',
sub_total => '780',
),
array( id => '79',
placed => '2013-09-18',
sub_total => '786'
),
array
(
id => '78',
placed => '2013-09-18',
sub_total => '756'
),
array(
id => '77',
placed => '2013-09-17',
sub_total => '786'
),
array(
id => '76',
placed => '2013-09-16',
sub_total => '756'
)
);
$result=array();
foreach($shop as $value)
{
if(!isset($result[$value['placed']]))
{
//echo $value['placed'];
//echo $result[$value['placed']];
$result[$value['placed']]=array('placed'=>$value['placed'],'sub_total'=>0);
}
$result[$value['placed']]['sub_total']+=$value['sub_total'];
}
print_r($result);
//print_r($shop);
?>
Related
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);
I have an array of farmer and their related crops and also crop related images. I want that array to farmer array with their related crops with image. I have to unique farmer and related crops can be different object in farmer array.
I use below query:
$q = $this->db->select("farmer_master.*, state_master.name as state_name,
district_master.name as district_name,
taluka_master.name as taluka_name, farmer_crop.crop_id
AS crops, farmer_crop.acre AS acres, crop_master.name as
crop_name, GROUP_CONCAT(farmer_crop_images.crop_image)
as crops_images")
->from("farmer_master")
->join("farmer_crop", "farmer_crop.farmer_id =
farmer_master.id","LEFT")
->join("crop_master", "crop_master.id = farmer_crop.crop_id","LEFT")
->join("state_master", "state_master.id =
farmer_master.state_id","LEFT")
->join("district_master", "district_master.id =
farmer_master.district_id","LEFT")
->join("taluka_master", "taluka_master.id =
farmer_master.taluka_id","LEFT")
->join("farmer_crop_images", "farmer_crop_images.farmer_crop_id =
farmer_crop.id","LEFT")
->where("farmer_master.sales_id", $sales_id)
->group_by("farmer_crop_images.farmer_crop_id")
->get();
and result is
$q->result_array();
I have an array like below:
Array
(
[0] => Array
(
[id] => 1
[farmer_name] => Mehul
[mobile] => 8401036474
[address] => Karanagar road
[village] => Nagarvel
[total_acre] => 100
[state_id] => 1
[district_id] => 10
[taluka_id] => 28
[sales_id] => 43
[created_at] => 2017-05-15 04:21:09
[state_name] => gujarat
[district_name] => bharuch
[taluka_name] => anklesvar
[crops] => 4
[acres] => 15
[crop_name] => green gram
[crops_images] => 1494836337726.jpg,1494739175265.jpg
)
[1] => Array
(
[id] => 1
[farmer_name] => Mehul
[mobile] => 8401036474
[address] => Karanagar road
[village] => Nagarvel
[total_acre] => 100
[state_id] => 1
[district_id] => 10
[taluka_id] => 28
[sales_id] => 43
[created_at] => 2017-05-15 04:21:09
[state_name] => gujarat
[district_name] => bharuch
[taluka_name] => anklesvar
[crops] => 3
[acres] => 70
[crop_name] => rice
[crops_images] => 1494836356691.jpg
)
)
And my desired result like below:
Array
(
[0] => Array
(
[id] => 1
[farmer_name] => Mehul
[mobile] => 8401036474
[address] => Karanagar road
[village] => Nagarvel
[total_acre] => 100
[state_id] => 1
[district_id] => 10
[taluka_id] => 28
[sales_id] => 43
[created_at] => 2017-05-15 04:21:09
[state_name] => gujarat
[district_name] => bharuch
[taluka_name] => anklesvar
[crops] => Array
(
[0] => Array
(
[crop_id] => 4
[acres] => 15
[crop_name] => green gram
[crops_images] => 1494836337726.jpg,1494739175265.jpg
)
[1] => Array
(
[crop_id] => 3
[acres] => 70
[crop_name] => rice
[crops_images] => 1494836356691.jpg
)
)
)
)
You have to first take get id of farmer with unique
$ids = array_unique(array_column($array, "id"));
// print_r($ids);exit; Array ( [0] => 1 )
$farmer_list_new = array();
for($i=0; $i<count($ids); $i++)
{
$first_time = true;
$farmer_list_new[$i] = array();
foreach( $farmer_list as $row )
{
if( $ids[$i] == $row['id'] )
{
if( $first_time )
{
$first_time = false;
$farmer_list_new[$i] = array(
'id' => $row['id'] ,
'farmer_name' => $row['farmer_name'] ,
'mobile' => $row['mobile'] ,
'address' => $row['address'] ,
'village' => $row['village'] ,
'total_acre' => $row['total_acre'] ,
'state_id' => $row['state_id'] ,
'district_id' => $row['district_id'] ,
'taluka_id' => $row['taluka_id'] ,
'sales_id' => $row['sales_id'] ,
'created_at' => $row['created_at'] ,
'state_name' => $row['state_name'] ,
'district_name' => $row['district_name'],
'taluka_name' => $row['taluka_name'] ,
'crops' => array()
);
}
$crop_images = explode(",", $row['crops_images']);
foreach($crop_images as $img){
$crop_images_url[] = $img;
}
$img_crops = implode(",", $crop_images_url);
$farmer_list_new[$i]['crops'][] = array(
'crop_id' => $row['crops'],
'acres' => $row['acres'],
'crop_name' => $row['crop_name'],
'crops_images' => $row['crops_images'],
);
}
}
}
From this below array:
Array
(
[0] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.05
[total_marks] => 2.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 52
)
[1] => Array
(
[tag_name] => Quant-Arithmetic
[student_marks] => 1.10
[total_marks] => 4.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 28
)
[2] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 0.20
[total_marks] => 1.00
[student_count] => 1
[level] => Easy
[overall_percentage] => 20
)
[3] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.00
[total_marks] => 6.00
[student_count] => 1
[level] => Medium
[overall_percentage] => 17
)
[4] => Array
(
[tag_name] => Quant-Algebra
[student_marks] => 1.50
[total_marks] => 6.00
[student_count] => 1
[level] => Hard
[overall_percentage] => 25
)
)
To some thing similar: As i need an array based on tag name with its all levels inside that array so that I can get the individual tag name with its level and percentage for further calculations
[tag_name]
{
[level]:[overall_percentage]
[level]:[overall_percentage]
.
.
}
.
.
.
$newArray = array();
foreach($yourarray as $item){
$newArray[$item['tag_name']][$item['level']] = $item['overall_percentage'];
}
This will add create a $newArray as follows:
Array(
'tag_name' => Array(
'Medium' => '27'
)
)
try this code
$array =array
(
'0' => array
(
'tag_name' => 'Quant-Arithmetic',
'student_marks' => ' 1.05',
'total_marks' => ' 2.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 52',
),
'1' => array
(
'tag_name' => ' Quant-Arithmetic',
'student_marks' => ' 1.10',
'total_marks' => ' 4.00',
'student_count' => ' 1',
'level' => ' Medium',
'overall_percentage' => ' 28',
),
'2' => array
(
'tag_name' => ' Quant-Algebra',
'student_marks' => ' 0.20',
'total_marks' => ' 1.00',
'student_count' => ' 1',
'level' => ' Easy',
'overall_percentage' => ' 20',
)
);
// declare a new array
$new_array = array();
foreach($array as $values){
// trim array elements
$trimmed_array=array_map('trim',$values);
if(isset($new_array[$trimmed_array['tag_name']])){
//add elements to array
$new_array[$trimmed_array['tag_name']][$trimmed_array['level']] = $trimmed_array['overall_percentage'];
}else{
// create new array
$new_array[$trimmed_array['tag_name']] = array($trimmed_array['level'] => $trimmed_array['overall_percentage']);
}
}
// php array
print_r($new_array);
// json
echo json_encode($new_array);
Out Put : array
Array
(
[Quant-Arithmetic] => Array
(
[Easy] => 52
[Medium] => 28
)
[Quant-Algebra] => Array
(
[Easy] => 20
)
)
Out Put : Json
{"Quant-Arithmetic":{"Easy":"52","Medium":"28"},"Quant-Algebra":{"Easy":"20"}}
I need to create an XML-RPC server that gets cities with their corresponding IDs. What I do as a response is looking weird to me because of unnecessary duplicate entries but I couldnt find a better way.
Array
(
[cityID] => Array
(
[0] => 34
[1] => 35
[2] => 06
)
[cityName] => Array
(
[0] => Istanbul
[1] => Izmir
[2] => Ankara
)
)
I implemented above response. With this implementation:
$response = array(
array(
'cityID' => array(array('34', '35', '06'), 'array'),
'cityName' => array(array('Istanbul', 'Izmir', 'Ankara'), 'array')
),
'struct'
);
The problem is I want to take a response like this :
Array
(
[cities] => Array
(
['34'] => 'Istanbul'
['35'] => 'Izmir'
['06'] => 'Ankara'
)
)
So I tried to implement it like this :
$response = array(
array(
'cities' => array(array('34'=>'Istanbul', '35'=>'Izmir', '06'=>'Ankara'), 'array')
),
'struct'
);
But it fails with this implementation. What am I doing wrong ?
Thanks
You have array like following
$response = array ( 'cityID' => array (
0 => 34,
1 => 35,
2 => 06
),
'cityName' => array(
0 => 'Istanbul',
1 => 'Izmir',
2 => 'Ankara'
)
);
$newarray = array();
foreach($response['cityID'] as $key => $cityid){
$newarray['cities'][$cityid] = $response['cityName'][$key];
}
print_r($newarray);
You will be getting the expected array.
Array
(
[cities] => Array
(
[34] => Istanbul
[35] => Izmir
[6] => Ankara
)
)
This is how I do it, in Code Igniter 3
$array = array ( 'cityID' => array (
0 => 34,
1 => 35,
2 => 06
),
'cityName' => array(
0 => 'Istanbul',
1 => 'Izmir',
2 => 'Ankara'
)
);
foreach($array['cityID'] as $key => $cityid){
$response[] = array(array(
$cityid => array($array['cityName'][$key],'string'),
),'struct');
}
return $this->xmlrpc->send_response(array($response,'array'));
I am trying to filter two arrays to get a final result with user ids from my mysql database
I have two arrays the first one:
print_r($arr_partner_id);
Array (
[0] => Array ( [id] => 335 [id_partner] => 0 )
[1] => Array ( [id] => 469 [id_partner] => 1 )
[2] => Array ( [id] => 457 [id_partner] => 1 )
[3] => Array ( [id] => 339 [id_partner] => 0 )
[4] => Array ( [id] => 361 [id_partner] => 0 ) )
and the second one:
print_r($arr_member_id);
Array (
[0] => 457
[1] => 469
[2] => 339
[3] => 361 )
now i want compare these two only with their ids and delete the ids that are not included in the "$arr_member_id" Array. This my "reference Array" that means i only need the ids (457,469,339,361)
for the final result it should be looking like this:
print_r($arr_partner_final_id);
Array (
[0] => Array ( [id] => 469 [id_partner] => 1 )
[1] => Array ( [id] => 457 [id_partner] => 1 )
[2] => Array ( [id] => 339 [id_partner] => 0 )
[3] => Array ( [id] => 361 [id_partner] => 0 ) )
i tryed it with foreach
foreach ($arr_partner_id as $key => $usr_ids) {
if($arr_partner_id[$key]['id'] == $arr_member_id[$key]) {
// do something
}
}
but the "keys" are different this should not working...
making it as simple, and using just one loop to loop through the array and checkin if the id is present in another set of array using in_array()
try this
for($i=0;$i<count($arr_partner_id);$i++){
if(!in_array($arr_partner_id[$i]['id'],$arr_member_id)){
unset($arr_partner_id[$i]);
}
}
print_r($arr_partner_id);
try it here
AND yes!! if you want seperate arrays for that then simply modify the code..create new array and push the elements that is present in array
$finalArray=array();
for($i=0;$i<count($arr_partner_id);$i++){
if(in_array($arr_partner_id[$i]['id'],$arr_member_id)){
$finalArray[]=$arr_partner_id[$i];
}
}
print_r($finalArray);
Try this (Working example : http://codepad.org/ApFcA3Zo)
<?php
$arr_partner_id=array (
'0' => array ( 'id' => 335, 'id_partner' => 0 ) ,
'1' => array ( 'id' => 469, 'id_partner' => 1 ) ,
'2' => array ( 'id' => 457, 'id_partner' => 1 ) ,
'3' => array ( 'id' => 339, 'id_partner' => 0 ) ,
'4' => array ( 'id' => 361, 'id_partner' => 0 ) ) ;
$arr_member_id=array (
'0' => 457 ,
'1' => 469 ,
'2' => 339 ,
'3' => 361 ) ;
$final =array();
foreach($arr_partner_id as $arr)
{
foreach($arr_member_id as $parr)
{
if($arr['id'] == $parr)
{
$final[]=$arr;
}
}
}
print_r($final);
?>
Maybe something like:
foreach ($arr_member_id as $usr_id){
foreach ($arr_partner_id as $partner){
if ($usr_id == $partner['id']) {$arr_partner_final_id[]=$partner;break;
}
}
Another solution (without explicit looping):
$arr_partner_id=array (
'0' => array( 'id' => 335, 'id_partner' => 0 ),
'1' => array( 'id' => 469, 'id_partner' => 1 ),
'2' => array( 'id' => 457, 'id_partner' => 1 ),
'3' => array( 'id' => 339, 'id_partner' => 0 ),
'4' => array( 'id' => 361, 'id_partner' => 0 ));
$arr_member_id=array (
'0' => 457,
'1' => 469,
'2' => 339,
'3' => 361);
function compare($v){global $arr_member_id;return in_array($v['id'], $arr_member_id);}
var_dump($arr_partner_id = array_filter($arr_partner_id, 'compare'));
better you use mysql itself do this task. but if you need to continue with this use in array function to check the second array as given below,
foreach ($arr_partner_id as $key => $usr_ids) {
if(in_array($usr_ids["id"], $arr_member_id)) {
// do something
}
}