Laravel Helper to merge Period arrays [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Laravel Version:7.0
I would like to know how to create this helper.
Input is date range array. For example:
$input1 = [2020-07-19, 2020-07-25];
$input2 = [2020-07-26, 2020-08-01];
$input3 = [2020-08-01, 2020-08-07];
$input4 = [2020-10-01, 2020-10-07];
$input5 = [2020-10-19, 2020-10-25];
I would like to make one helper function.
function mergeDate($array)
{
...
}
So when I use this helper, I would like to get as following result.
$array = [$input1, $input2, $input3, $input4, $input5];
$mergedResult = mergeDate($array);
$mergedResult[0] = [2020-07-19, 2020-08-07];
$mergedResult[1] = [2020-10-01, 2020-10-07];
$mergedResult[2] = [2020-10-19, 2020-10-25];
Can anyone help me how to make mergeDate function?
Input period elements aren't overlapped.
Thank you!

This would be my first guess at how to solve it.
public function merge($array){
$results = [];
foreach ($array as $element){
if (sizeof($results) == 0){
array_push($results,$element);
}else{
$found = null;
foreach ($results as $key => $r){
if (Carbon::parse($element[0])->equalTo(Carbon::parse($r[1])))
{
$found = $key;
break;
}
}
if (!is_null($found)){
$results[$found][1] = $element[1];
}else{
array_push($results, $element);
}
}
}
return $results;
}
It is a simple take on the problem. If our resulting array is empty we add the first element otherwise we iterate over the results to find a matching pair of the elements end date and the start date of the item in the results array. If we find a matching start end pair we replace the results end value with the elements end value. Otherwise we have no overlap and we can add it as a new item to the results array.
An interesting library to use would be the Spatie/Period library.
https://github.com/spatie/period
#edit
since the array is not sorted as mentioned in a comment above, you would have to sort it prior.

Related

how to concatenate multiple strings with commas if there is the same array data [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have the array data as drawn
image description here
and I want to display data like this
0 = "16-11-1996 / IGD"
01 = "CBC", "DIFF"
04 = "GLUS "," UR "," CRE "
I tried to use this PHP splitting arrays into groups based on equal values method but it was not what I expected.
i am just learning coding and i am not what way or what keywords should i use to find a solution. i hope someone can help me,
A simple solution that uses foreach to create a new array.
Input:
$data = [
["OTHER_ID"=>"16-11-1996 / IGD", "SPEC_TYPE"=>"0"],
["OTHER_ID"=>"CBC", "SPEC_TYPE"=>"01"],
["OTHER_ID"=>"DIFF", "SPEC_TYPE"=>"01"],
["OTHER_ID"=>"GLUS", "SPEC_TYPE"=>"04"],
["OTHER_ID"=>"UR", "SPEC_TYPE"=>"04"],
["OTHER_ID"=>"CRE", "SPEC_TYPE"=>"04"],
];
Create a array grouped by "SPEC_TYPE".
$arr = [];
foreach($data as $row){
$key = $row["SPEC_TYPE"];
$arr[$key][] = $row["OTHER_ID"];
}
The array has "SPEC_TYPE" as a key and all "OTHER_ID" in a subarray. With another foreach we can now do the output. We cleverly use the implode function for this.
foreach($arr as $key => $others){
echo $key.' = "'.implode('", "',$others).'"<br>';
}
Output for the example data above:
0 = "16-11-1996 / IGD"
01 = "CBC", "DIFF"
04 = "GLUS", "UR", "CRE"
Here you can try it yourself.
Try this I kept it as simple as I could since you are a beginner. First we take the unique spec types by using array_map to take out only spec types and then array_unique for taking out the unique values. After that for every spec id we would want to search the matching spec types and filter them out. For this we use array_filter and then again another array_map to take out the other ids and finally an implode function for converting the array into a string.
$data = [
["OTHER_ID"=>"A", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"B", "SPEC_TYPE"=>"2"],
["OTHER_ID"=>"C", "SPEC_TYPE"=>"1"],
["OTHER_ID"=>"D", "SPEC_TYPE"=>"3"],
["OTHER_ID"=>"E", "SPEC_TYPE"=>"3"]
];
$result = array_map(function ($a) { return $a["SPEC_TYPE"]; }, $data);
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_map(function ($a) { return $a["OTHER_ID"]; }, $response[$r]), ", ");
}
echo json_encode($response);
// {"1":"A, C","2":"B","3":"D, E"};
In laravel you have helper functions to reduce the unnecessary code so we can reduce our array_map with array_pluck. Also array_where could be used in place of array_filter but in this case it would have the same callback and functionality so let's keep the filter for now. Below code isn't tested but should do the thing.
$result = array_pluck($data, "SPEC_TYPE");
$result = array_unique($result);
$response=[];
foreach($result as $r) {
$response[$r] = array_filter($data, function ($d) use($r) { return $r==$d["SPEC_TYPE"]; });
$response[$r] = implode(array_pluck($response[$r], "OTHER_ID"), ", ");
}
Resources to study more on this:
Laravel helper functions: https://laravel.com/docs/5.0/helpers
PHP array functions: https://www.w3schools.com/php/php_ref_array.asp

How to sort an array with name, date and quantity? PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this array and I would like to sort the dates for the graphs.[]
1
Before I was using this function because I was only bringing in the array example ````$data[$date] = $total``` but now I am bringing in the name, date and total.
foreach ($_data_ as $key => $value) {
$_date[] = $value->fecha;
$_dataOpportunities[$value->name][$value->fecha] = $value->total;
}
foreach ($_dataOpportunities as $key => $value) {
for ($i=0; $i < count($_date) ; $i++) {
if (!array_key_exists($_date[$i],$value)) {
$_dataOpportunities[$key][$_date[$i]] = 0;
}
}
}
//Order by date //Not order
foreach ($_dataOpportunities as $key => $value) {
//dd($value);
uksort($value,['self','compare_date_keys']);
}
dd($_dataOpportunities);
public static function compare_date_keys($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
The dd($value) returns this:
And when it exits the foreach and returns the variable dd($_dataOpportunities); it returns me the following:
Dates are still not sorted.
I tried uksort and usort and still the date order does not work.
Assuming the multi-dimensional array is $array:
function key_cmp_date($dt1, $dt2) {
return strtotime($dt1) - strtotime($dt2);
}
foreach($array as $key=>$val){
uksort($array[$key],"key_cmp_date");
}
I haven't tested it, but this should suffice.
Try using ksort($arr) function to sort the array. I haven't tried this, but I think this will work.

different results array shortcode PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a question about the differents between the normal array code and the shortcode.
The output from the shortcode version has all the results.
But the normal code has only the last record of the data from the database.
Please is there somebody who can explain this?
Below the shortcode
<?php
while ($data = mysqli_fetch_assoc($result)) {
$output[$data['category']][] = $data['type'];
}
?>
Below the normal code
<?php
while ($data = mysqli_fetch_assoc($result)) {
//alleen laatste database result
$output = array($data['category'] => array($data['type']));
}
?>
When you assign
$output = <anything>;
you discard all the previous contents of $output, and replace it with the value of <anything>. So each time through the loop in the second version, you replace the variable with the data from the current row. When the loop is done, it just has the data from the last row.
You don't want to replace all of $output. It should be a multi-dimensional array, where the first dimension is associative with categories as keys, and the second dimension is an array of all type values in that category. Assigning to
$output[$data['category']][]
does two things:
$output[$data['category']] creates the category key in the first dimension if it doesn't already exist.
Assigning to [] pushes a new element onto the array in the second dimension.
It's equivalent to the following long code
while ($data = mysqli_fetch_assoc($result)) {
$cat = $data['category'];
if (!isset($output[$cat])) {
$output[$cat] = array();
}
array_push($output[$cat], $data['type']);
}

Add new values to foreach loop from inside the loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
Is possible to add new values to the array that the foreach is working with? So it will run (n+x) where n is the number of elements of the array before the foreach starts and x is the number of elements that were added to the array.
Yes, I tested.. and looks like NO.. so I'd like to know if I can do something to this work.
foreach($pages_to_visit as $key => $source){
global $products;
$links = baixarSource($source);
foreach($links as $link){
global $products;
global $pages_to_visit;
if(preg_match("/somestore\.com/i", $link)){
if(!in_array($link, $pages_to_visit)){
$pages_to_visit[] = $link;
}else if(preg_match("/\/produto\//i", $link) && !in_array($link, $products)){
$products[] = $link;
echo $link."\n";
}
}
}
unset($pages_to_visit[$key]);
sleep(0.2);
}
As you already figured out, using foreach() it is not possible, however when you use for() the task becomes quite easy:
for ($i=0; $i<count($array); $i++) {
//code
}
This is due to count($array) being (re)calculated before every iteration. You can also use a variable that you increment yourself (incrementing is a way easier task than counting an array)
$max = count($array);
for ($i=0; $i<$max; $i++) {
//code
//when push an element just do $max++;
}
Of course this will only work with numerical indices but that seems to be the case here.
You need to specify the "runner" variable as a reference in the foreach code if you want to modify the array itself from within the foreach.
http://us2.php.net/manual/en/control-structures.foreach.php
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Example (will only count to 9):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as $blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}
Example2 (this time it will count to 10 using the additional element added from inside the foreach):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as &$blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}
Not sure if I get your question right... I think what you try to do doesn't make much sense at all any way.
echo $countBefore = count($data);
foreach ($data $as $value) {
$data[] = 'Some new value';
}
echo $countAfter = count($data);

PHP get value of array by position [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am pulling the latest 3 news articles from my database and I need to access them by the order they were pulled from, so first position in the array, second position and so on to display them in order in random sections of my web page. I came across accessing the array key but that is not working, where am I going wrong? Thanks in advance!
$value = array_slice($blog, 0, 1);
echo $value;
I think you are looking for a foreach loop or something like that:
$blog = array('foo', 'bar', 'cat');
foreach ($blog as $article) {
echo $article;
}
/**
* Gives you:
*
foo
bar
cat
*/
But if you want to do it with functions, you can use array_shift. This will remove the first element from an array and return that:
$article1 = array_shift($blog); // $blog is now `array('bar', 'cat')`
echo $article1; // >> foo
$article2 = array_shift($blog); // $blog is now `array('cat')`
echo $article2; // >> bar
$article3 = array_shift($blog); // $blog is now `array()`
echo $article2; // >> cat
Or if you want to keep the original $blog array, use array pointer functions like current, next, prev, reset and end:
reset($blog);
$article1 = current($blog); // >> foo
$article2 = next($blog); // >> bar
$article3 = next($blog); // >> cat
Use this :
$value = array_shift($blog);
To get second one
$value2 = array_shift($blog);
and third :
$value3 = array_shift($blog);
You have three different ways to accomplish this:
1. Call array_shift($blog) each time you want to get the next value.
$value = array_shift($blog);
Each time you do the array_shift it will return the next entry in the array.
Function array_pop is similar but returns the last entry in the array each time.
2. Simply access each entry of the array using the index
This gives the first entry in the array:
$value = $blog[0]
This gives the second entry in the array:
$value = $blog[1]
This gives the n'th value in the array:
$value = $blog[n-1];
3. Or finally you can simply loop through the array and echo out each entry (may not be suitable if you don't want to sequentially echo out the entries in the same place)
foreach ($blog as $blog_entry) {
echo $blog_entry;
}

Categories