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 7 years ago.
Improve this question
Heres what I want to do:
<?php
$array = array("array1" => array(), "array2" => array());
function mdparser(){
for($i = 0;$i < func_num_args();$i++){
//foreach arguement go 1 child deeper
return $array["array1"] //if second argument exists ["array2"];
?>
I need this to parse multidimensional arrays independantly , so I can use it on any Multi dimensional array.
Still just guessing at what you're trying to achieve
$this->myArray = array("key1" => array("key2" => array(1,2,3)));
protected function mdparser(){
$result = $this->myArray;
for($i = 0;$i < func_num_args();$i++){
$result = $result[func_get_arg($i)];
}
return $result;
}
$result = this->mdparser('key1', 'key2', 1);
PHP >= 5.6 allows variadics to simplify this:
protected function mdparser(...$args){
$result = $this->myArray;
foreach($args as $arg){
$result = $result[$arg];
}
return $result;
}
Just pass the array to the method when you call it, assuming you are calling it from somewhere where $array is in scope
Also change the array you are building so you have a known, easily processible index i.e. 0.1.2... and not 'array1', 'array2',....
<?php
$array = array( array(), array() );
function mdparser($array){
return $array[count($array)-1];
}
$last_array = mdparser($array);
?>
This should return the last array within the outer array.
Doesnt matter now ive found a way thanks anyways:
function search_array(){
$args = func_get_args();
$arg_num = func_num_args();
for($i = 0;$i < $arg_num;$i++){
$arg = $args[$i];
//foreach arguement go 1 child deeper
$array = $this->array[$arg];
$this->array = $array;
//if second argument exists ["array2"];
}
}
Related
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
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.
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.
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 5 years ago.
Improve this question
If I have an array like this:
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
How to print a $cars['name'] where $cars[Year] = 2013, is that possible in the array as we can do in MySQL? As we know with MySQL we can do:
select * from table where //condition
So, how this can be done in arrays?
You could loop through each element in the array and using an 'if' statement echo the name of the car if the year is 2013
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
foreach ($cars as $value) {
if($value[Year] == 2013){
echo $value[name] ."<br>";
}
}
And also solution with array_filter, because you will probably have multiple cars with same year.
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
$filtered_cars = array_filter($cars, function ($item) {
return $item['Year'] === '2013';
});
print_r(current($filtered_cars)['name']);
An example with the isFromYear function accepting the year as a parameter:
<?php
$cars = array (
array("name"=>"jeep","Year"=>"2012"),
array("name"=>"ferrari","Year"=>"2017"),
array("name"=>"jaguar","Year"=>"2013")
);
class YearFilter {
private $year;
function __construct($year) {
$this->year = $year;
}
function isFromYear($i) {
return $i["Year"] == $this->year;
}
}
$matches = array_filter($cars, array(new YearFilter("2013"), 'isFromYear'));
print_r($matches);
?>
You can use array_filter() and pass an conditional function as the second argument along with your array. As an example in your case:
function filterArray($value){
if($value['Year'] == "2013")
return $value['name'];
}
$filteredArray = array_filter($fullArray, 'filterArray');
So if we passed an array that looks like:
$fullArray = array (
array("name"=>"John","Year"=>"2012"),
array("name"=>"Doe","Year"=>"2017"),
array("name"=>"Martin","Year"=>"2013")
);
Output would be:
Array
(
[2] => Array
(
[name] => Martin
[Year] => 2013
)
)
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);