Related
I'm a bit stuck here
I have an array that I'm exporting with laravel excel and I'm basically creating a category row and then all subsequent item rows that belong to that category.
How can I properly add a counter for every array_push to the groupItem array so that I can count every row between the groupItem push and set the row with the category info to bold?
Basically I only want to bold the row that has the data for category_code, category_name and category_desc so I would need to iterate based on the array_push for the category info I believe
I think I would need to set a count, increase count for the categoryItem array_push, store that count in an array and then set those array stored rows to bold?
$allgroupResult= array();
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["category_code"] = $group->category_code;
$groupItem["category_name"] = $group->category_name;
$groupItem["category_desc"] = $group->category_desc;
array_push($allgroupResult, $groupItem);
foreach($group->skus as $sku){
$skuItem = array();
$skuItem["item_code"] = $sku->sku_info->item->item_code;
$skuItem["identifier"] = $sku->sku_info->identifier;
foreach($sku->prices as $price => $amount){
$skuItem[] = $amount;
}
$skuItem[] = strip_tags(html_entity_decode($sku->sku_info->item->desc));
foreach ($sku->sku_info->details as $details) {
$skuItem[] = $details->details1;
$skuItem[] = $details->details2;
$skuItem[] = $details->details3;
}
array_push($allgroupResult, $skuItem);
}
}
$name = 'File Export';
$build = Excel::create($name, function ($excel) use ($allgroupResult) {
$excel->setTitle('File Export');
$excel->sheet('File Export', function ($sheet) use ($allgroupResult) {
$sheet->fromArray($allgroupResult);
// bold the column headers
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
// $count = 2;
// foreach($excelRows as $one){
// $sheet->fromArray($one, null, 'A2');
// $sheet->row($count, function($row) {
// $row->setFontWeight('bold');
// });
// $count += count( $one ) + 1;
// }
// set the width for the columns that are used
$sheet->setWidth('A', 10);
$sheet->setWidth('B', 24);
$sheet->setWidth('C', 20);
$sheet->setWidth('D', 12);
$sheet->setWidth('E', 10);
$sheet->setWidth('F', 16);
$sheet->setWidth('G', 16);
$sheet->setWidth('H', 16);
$sheet->setWidth('I', 16);
$sheet->setWidth('J', 16);
$sheet->setWidth('K', 16);
});
})->download('xlsx');
Why not creating another folded array inside $allgroupResult for each category, so having structure like this:
array(1) {
[0] =>
array(4) {
'category_code' =>
string(13) "category_code"
'category_name' =>
string(13) "category_name"
'category_desc' =>
string(13) "category_desc"
'skus' =>
array(3) {
[0] =>
string(4) "sku1"
[1] =>
string(4) "sku2"
[2] =>
string(4) "sku3"
}
}
}
and then you can just do count($item['skus']) whenever you need to get the number of products in every category. In order to do this , try the following modification to your foreach loop:
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["category_code"] = $group->category_code;
$groupItem["category_name"] = $group->category_name;
$groupItem["category_desc"] = $group->category_desc;
$groupItem["skus"] = array();
foreach($group->skus as $sku){
$skuItem = array();
$skuItem["item_code"] = $sku->sku_info->item->item_code;
$skuItem["identifier"] = $sku->sku_info->identifier;
foreach($sku->prices as $price => $amount){
$skuItem[] = $amount;
}
$skuItem[] = strip_tags(html_entity_decode($sku->sku_info->item->desc));
foreach ($sku->sku_info->details as $details) {
$skuItem[] = $details->details1;
$skuItem[] = $details->details2;
$skuItem[] = $details->details3;
}
$groupItem["skus"][] = $skuItem;
}
$allgroupResult[] = $groupItem;
}
foreach ($ids as $key => $value) {
$settlement_data = $this->settlement_model->getSettlementData($value);
foreach ($settlement_data as $key_date => $price) {
$temp[] = array($key_date, (float)$price['settlement_price']);
}
$this->load->library('xlsxwriter');
$file = new XLSXWriter();
$first_row = array();
if ($temp) {
$first_row = array_fill(0, count($temp[0]), "");
}
//add one empty row at the beginning of array
array_unshift($temp, $first_row);
//add title row at the beginning of array (above the empty one)
$title = 'test title';
$file->writeSheet(array_values($temp), 'Mytest', $headers, $title);
$file->downloadAsFile('test' . ".xlsx");
die();
}
The sample data for $settlement data is as follows:
array(7571) {
["2017-05-20"]=>
array(4) {
["settlement_price"]=>
string(15) "10.001"
}
["2017-05-21"]=>
array(4) {
["settlement_price"]=>
string(14) "15.726"
}
["2017-05-22"]=>
array(4) {
["settlement_price"]=>
string(15) "15.729352220997"
}
write now only the dates and price of one id is written to the excel file.How can i write the prices of other ids as well corresponding to the date?
example:
Date Price of id1 price of id2
2017-05-20 10.001 20.001
2017-05-21 15.726 70.001
In PHP, how do I loop through the following JSON Object's date key, if the date value are the same then merge the time:
[
{
date: "27-06-2017",
time: "1430"
},
{
date: "27-06-2017",
time: "1500"
},
{
date: "28-06-2017",
time: "0930"
},
{
date: "28-06-2017",
time: "0915"
}
]
Result should looks like this:
[
{
date: "27-06-2017",
time: [{"1430","1500"}]
}, {
date: "28-06-2017",
time: [{"0930, 0915"}]
}
]
Should I create an empty array, then the looping through the JSON and recreate a new JSON? Is there any better way or any solution to reference?
Thank you!
This solution is a little overhead, but if you are sure that your data is sequential and sorted, you can use array_count_values and array_map:
$count = array_count_values(array_column($array, 'date'));
$times = array_column($array, 'time');
$grouped = array_map(function ($date, $count) use (&$times) {
return [
'date' => $date,
'time' => array_splice($times, 0, $count)
];
}, array_keys($count), $count);
Here is working demo.
Another Idea to do this is
<?php
$string = '[{"date": "27-06-2017","time": "1430"},{"date": "27-06-2017","time": "1500"},{"date": "28-06-2017","time": "0930"},{"date": "28-06-2017","time": "0915"}]';
$arrs = json_decode($string);
$main = array();
$temp = array();
foreach($arrs as $arr){
if(in_array($arr->date,$temp)){
$main[$arr->date]['time'][] = $arr->time;
}else{
$main[$arr->date]['date'] = $arr->date;
$main[$arr->date]['time'][] = $arr->time;
$temp[] = $arr->date;
}
}
echo json_encode($main);
?>
live demo : https://eval.in/787695
Please try this:
$a = [] // Your input array
$op= [];//output array
foreach($a as $key => $val){
$key = $val['date'];
$op[$key][] = $val['time'];
}
$op2 = [];
foreach($op as $key => $val){
$op2[] = ['date' => $key, 'time' => $val];
}
// create the "final" array
$final = [];
// loop the JSON (assigned to $l)
foreach($l as $o) {
// assign $final[{date}] = to be a new object if it doesn't already exist
if(empty($final[$o->date])) {
$final[$o->date] = (object) ['date' => $o->date, 'time' => [$o->time]];
}
// ... otherwise, if it does exist, just append this time to the array
else {
$final[$o->date]->time[] = $o->time;
}
}
// to get you back to a zero-indexed array
$final = array_values($final);
The "final" array is created with date based indexes initially so that you can determine whether they've been set or not to allow you to manipulate the correct "time" arrays.
They're just removed at the end by dropping $final into array_values() to get the zero-indexed array you're after.
json_encode($final) will give you want you want as a JSON:
[{"date":"27-06-2017","time":["1430","1500"]},{"date":"28-06-2017","time":["0930","0915"]}]
Yet another solution :
$d = [];
$dizi = array_map(function ($value) use (&$d) {
if (array_key_exists($value->date, $d)) {
array_push($d[$value->date]['time'], $value->time);
} else {
$d[$value->date] = [
'date' => $value->date,
'time' => [$value->time]
];
}
}, $array);
echo json_encode(array_values($d));
This post almost answered this question for me, but I have a specific need and didn't find what I sought there. This lies right outside my experience; couldn't quite wrap my head around it, so all I really need is a point in the right direction.
Let's say I have an array as follows:
array(5) {
[0]=> "2013-02-18 05:14:54"
[1]=> "2013-02-12 01:44:03"
[2]=> "2013-02-05 16:25:07"
[3]=> "2013-01-29 02:00:15"
[4]=> "2013-01-27 18:33:45"
}
I would like to have a way to provide a date ("2013-02-04 14:11:16", for instance), and have a function determine the closest match to this in the array (which would be "2013-02-05 16:25:07" in this case).
I'd appreciate any tips. Thanks! :)
I may not have the best naming conventions, but here goes.
I calculate the intervals between the array of dates and the given date. I then do a sort, to find the "smallest" difference.
$dates = array
(
'0'=> "2013-02-18 05:14:54",
'1'=> "2013-02-12 01:44:03",
'2'=> "2013-02-05 16:25:07",
'3'=> "2013-01-29 02:00:15",
'4'=> "2013-01-27 18:33:45"
);
function find_closest($array, $date)
{
//$count = 0;
foreach($array as $day)
{
//$interval[$count] = abs(strtotime($date) - strtotime($day));
$interval[] = abs(strtotime($date) - strtotime($day));
//$count++;
}
asort($interval);
$closest = key($interval);
echo $array[$closest];
}
find_closest($dates, "2013-02-18 05:14:55");
If I understand your question perfectly then this will solve your problem.
Tested Code
<?php
$dates = array
(
'0' => "2013-02-18 05:14:54",
'1' => "2013-02-12 01:44:03",
'2' => "2013-02-05 16:25:07",
'3' => "2013-01-29 02:00:15",
'4' => "2013-01-27 18:33:45"
);
function closest($dates, $findate)
{
$newDates = array();
foreach($dates as $date)
{
$newDates[] = strtotime($date);
}
echo "<pre>";
print_r($newDates);
echo "</pre>";
sort($newDates);
foreach ($newDates as $a)
{
if ($a >= strtotime($findate))
return $a;
}
return end($newDates);
}
$values = closest($dates, date('2013-02-04 14:11:16'));
echo date('Y-m-d h:i:s', $values);
?>
Suppose your array is bigger and that you have dates over the period 2009-10-01 to 2019-10-01. Lets now compare two approach: a. looping-array approach vs b. sorting-indexing-array approach.
<?php
$period = new DatePeriod(
new DateTime('2009-10-01 00:00:00'),
new DateInterval('P3D'),
new DateTime('2019-10-01 00:00:00')
);
foreach($period as $date){
$dates[] = $date->format('Y-m-d');
};
$today = '2019-08-18 13:00:15';
function custom_sort($array){
sort($array);
return $array;
}
function nearest_date_key($array, $today){
//push today to the array, sort the array,
//find the nearest day value of the sorted array and return key
array_push($array, $today);
$sorted_dates = custom_sort($array);
$find_today_key = array_search($today, $sorted_dates);
$nearest_date = array_slice($sorted_dates, $find_today_key + 1, 1);
return array_search($nearest_date[0], $array);
}
function find_closest($array, $today)
{
//$count = 0;
foreach($array as $day)
{
//$interval[$count] = abs(strtotime($date) - strtotime($day));
$interval[] = abs(strtotime($today) - strtotime($day));
//$count++;
}
asort($interval);
$closest = key($interval);
return $closest;
}
$start = microtime(true);
$result_a = nearest_date_key($dates, $today);
$time_elapsed_secs_a = microtime(true) - $start;
$start = microtime(true);
$result_b = find_closest($dates, $today);
$time_elapsed_secs_b = microtime(true) - $start;
?>
Printing the results gives (http://phptester.net/)
result time_elapsed
loop approach (a) 1203 0.00630
sorting index approach (b) 1203 0.00062
Which is a huge time elapsed gain. We divided by ten the waiting time
Just try this:
$date = array(
[0]=> "2013-02-18 05:14:54"
[1]=> "2013-02-12 01:44:03"
[2]=> "2013-02-05 16:25:07"
[3]=> "2013-01-29 02:00:15"
[4]=> "2013-01-27 18:33:45");
$baseDate = date_create('2009-10-11');
$count = count($date);
for($loop=0;$count>$loop;$loop++) {
$datetime = date_create($date[$loop]);
$interval = date_diff($baseDate, $datetime);
$newDate[$interval->format('%s')] = $date[$loop];
}
ksort($newDate);
foreach($newDate as $key=>$value) {
echo $value;
break;
}
Your first element will the the closest match date.
Note: Please test it before you use.
This post helped me think of a solution to my similar problem, so am dropping it here.
Given an array of dates, I needed to find the closest date, before or equal, to last Sunday.
Here's what I did without using any custom functions:
$all_dates = [
'20210328',
'20210321',
'20210314',
'20210307',
];
$last_sunday = date( 'Ymd', strtotime( date( 'Ymd' ) . 'last sunday')); //20210321
$latest_date_index;
foreach( $all_dates as $index => $date ) {
$date_obj = date_create_from_format( 'Ymd', $date );
$last_sunday_obj = date_create_from_format( 'Ymd', $last_sunday );
if ( $date_obj <= $last_sunday_obj ) {
$latest_date_index = $index;
break;
}
}
echo "latest date from array: $all_dates[$latest_date_index]";
echo "array of all past dates from array: " . var_dump(array_slice($all_dates, $latest_date_index));
this way also you can get sorted datetime array
function order_date_time($date_times=array(),$compare=null,$action=1){
$interval=0;
$order_date_time=array();
if(empty($date_times)){
return array();
}
foreach ($date_times as $date_time) {
$interval = strtotime($compare)-strtotime($date_time);
$order_date_time[$interval]=$date_time;
}
if(empty($compare)){
krsort($order_date_time);
return isset($order_date_time) && !empty($order_date_time)?array_values($order_date_time):array();
}else{
$order_date_time=array_values($order_date_time);
$compare_index=array_search($compare,$order_date_time);
return $order_date_time[$compare_index+$action]??$order_date_time[$compare_index];
}
}
//input
$array=array
(
2022-02-23 19:58:00
2022-03-02 18:00:00
2022-02-09 18:00:00
)
$close_dat_time=order_date_time($array,'2022-02-23 19:58:00')
// output
2022-02-09 18:00:00
I have an array of my inventory (ITEMS A & B)
Items A & B are sold as sets of 1 x A & 2 x B.
The items also have various properties which don't affect how they are distributed into sets.
For example:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
I want to redistribute the array $inventory to create $set(s) such that
$set[0] => Array
(
[0] => array(A,PINK)
[1] => array(B,RED)
[2] => array(B,BLUE)
)
$set[1] => Array
(
[0] => array(A,MAUVE)
[1] => array(B,YELLOW)
[2] => array(B,GREEN)
)
$set[2] => Array
(
[0] => array(A,ORANGE)
[1] => array(B,BLACK)
[2] => NULL
)
$set[3] => Array
(
[0] => array(A,GREY)
[1] => NULL
[2] => NULL
)
As you can see. The items are redistributed in the order in which they appear in the inventory to create a set of 1 x A & 2 x B. The colour doesn't matter when creating the set. But I need to be able to find out what colour went into which set after the $set array is created. Sets are created until all inventory is exhausted. Where an inventory item doesn't exist to go into a set, a NULL value is inserted.
Thanks in advance!
I've assumed that all A's come before all B's:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
for($b_start_index = 0;$b_start_index<count($inventory);$b_start_index++) {
if($inventory[$b_start_index][0] == 'B') {
break;
}
}
$set = array();
for($i=0,$j=$b_start_index;$i!=$b_start_index;$i++,$j+=2) {
isset($inventory[$j])?$temp1=$inventory[$j]:$temp1 = null;
isset($inventory[$j+1])?$temp2=$inventory[$j+1]:$temp2 = null;
$set[] = array( $inventory[$i], $temp1, $temp2);
}
To make it easier to use your array, you should make it something like this
$inv['A'] = array(
'PINK',
'MAUVE',
'ORANGE',
'GREY'
);
$inv['B'] = array(
'RED',
'BLUE',
'YELLOW',
'GREEN',
'BLACK'
);
This way you can loop through them separately.
$createdSets = $setsRecord = $bTemp = array();
$bMarker = 1;
$aIndex = $bIndex = 0;
foreach($inv['A'] as $singles){
$bTemp[] = $singles;
$setsRecord[$singles][] = $aIndex;
for($i=$bIndex; $i < ($bMarker*2); ++$i) {
//echo $bIndex.' - '.($bMarker*2).'<br/>';
if(empty($inv['B'][$i])) {
$bTemp[] = 'null';
} else {
$bTemp[] = $inv['B'][$i];
$setsRecord[$inv['B'][$i]][] = $aIndex;
}
}
$createdSets[] = $bTemp;
$bTemp = array();
++$bMarker;
++$aIndex;
$bIndex = $bIndex + 2;
}
echo '<pre>';
print_r($createdSets);
print_r($setsRecord);
echo '</pre>';
To turn your array into an associative array, something like this can be done
<?php
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
$inv = array();
foreach($inventory as $item){
$inv[$item[0]][] = $item[1];
}
echo '<pre>';
print_r($inv);
echo '</pre>';
Maybe you can use this function, assuming that:
... $inventory is already sorted (all A come before B)
... $inventory is a numeric array staring at index zero
// $set is the collection to which the generated sets are appended
// $inventory is your inventory, see the assumptions above
// $aCount - the number of A elements in a set
// $bCount - the number of B elements in a set
function makeSets(array &$sets, array $inventory, $aCount, $bCount) {
// extract $aItems from $inventory and shorten $inventory by $aCount
$aItems = array_splice($inventory, 0, $aCount);
$bItems = array();
// iterate over $inventory until a B item is found
foreach($inventory as $index => $item) {
if($item[0] == 'B') {
// extract $bItems from $inventory and shorten $inventory by $bCount
// break out of foreach loop after that
$bItems = array_splice($inventory, $index, $bCount);
break;
}
}
// append $aItems and $bItems to $sets, padd this array with null if
// less then $aCount + $bCount added
$sets[] = array_pad(array_merge($aItems, $bItems), $aCount + $bCount, null);
// if there are still values left in $inventory, call 'makeSets' again
if(count($inventory) > 0) makeSets($sets, $inventory, $aCount, $bCount);
}
$sets = array();
makeSets($sets, $inventory, 1, 2);
print_r($sets);
Since you mentioned that you dont have that much experience with arrays, here are the links to the php documentation for the functions I used in the above code:
array_splice — Remove a portion of the array and replace it with something else
array_merge — Merge one or more arrays
array_pad — Pad array to the specified length with a value
This code sorts inventory without any assumption on inventory ordering. You can specify pattern (in $aPattern), and order is obeyed. It also fills lacking entries with given default value.
<?php
# config
$aInventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK"),
array("C","cRED"),
array("C","cBLUE"),
array("C","cYELLOW"),
array("C","cGREEN"),
array("C","cBLACK")
);
$aPattern = array('A','B','A','C');
$mDefault = null;
# preparation
$aCounter = array_count_values($aPattern);
$aCurrentCounter = $aCurrentIndex = array_fill_keys(array_unique($aPattern),0);
$aPositions = array();
$aFill = array();
foreach ($aPattern as $nPosition=>$sElement){
$aPositions[$sElement] = array_keys($aPattern, $sElement);
$aFill[$sElement] = array_fill_keys($aPositions[$sElement], $mDefault);
} // foreach
$nTotalLine = count ($aPattern);
$aResult = array();
# main loop
foreach ($aInventory as $aItem){
$sElement = $aItem[0];
$nNeed = $aCounter[$sElement];
$nHas = $aCurrentCounter[$sElement];
if ($nHas == $nNeed){
$aCurrentIndex[$sElement]++;
$aCurrentCounter[$sElement] = 1;
} else {
$aCurrentCounter[$sElement]++;
} // if
$nCurrentIndex = $aCurrentIndex[$sElement];
if (!isset($aResult[$nCurrentIndex])){
$aResult[$nCurrentIndex] = array();
} // if
$nCurrentPosition = $aPositions[$sElement][$aCurrentCounter[$sElement]-1];
$aResult[$nCurrentIndex][$nCurrentPosition] = $aItem;
} // foreach
foreach ($aResult as &$aLine){
if (count($aLine)<$nTotalLine){
foreach ($aPositions as $sElement=>$aElementPositions){
$nCurrentElements = count(array_keys($aLine,$sElement));
if ($aCounter[$sElement] != $nCurrentElements){
$aLine = $aLine + $aFill[$sElement];
} // if
} // foreach
} // if
ksort($aLine);
# add empty items here
} // foreach
# output
var_dump($aResult);
Generic solution that requires you to specify a pattern of the form
$pattern = array('A','B','B');
The output will be in
$result = array();
The code :
// Convert to associative array
$inv = array();
foreach($inventory as $item)
$inv[$item[0]][] = $item[1];
// Position counters : int -> int
$count = array_fill(0, count($pattern),0);
$out = 0; // Number of counters that are "out" == "too far"
// Progression
while($out < count($count))
{
$elem = array();
// Select and increment corresponding counter
foreach($pattern as $i => $pat)
{
$elem[] = $inv[ $pat ][ $count[$i]++ ];
if($count[$i] == count($inv[$pat]))
$out++;
}
$result[] = $elem;
}