working with two arrays in foreach, is this example possible? - php

I'm working with two arrays, $local and $national. Currently, they're both within their own separate foreach loops, which I'm using as follows:
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
foreach($list as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
}
}
foreach($national as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numbernational[] = $rows;
}
}
Is there a way however to merge these two foreach functions? I've tried the following:
foreach(array_merge($list, $national) as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}
But unfortunately when I do a print_r on both $numberlist and $numbernational, they're both returning the exact same array. In hindsight this makes sense to me now, so I wonder if I can do something along the lines of:
foreach($list as $row, $national as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $row;
$numbernational[] = $rows;
}
}
Both the $list and $national arrays are the same size.

You can iterate over both arrays in a single pass using SPL's MultipleIterator
$numberlist = [];
$numbernational = [];
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($list));
$mi->attachIterator(new ArrayIterator($national));
$result = array();
foreach($mi as list($listRow, $nationalRow)) {
if (strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)) {
$numberlist[] = $listRow;
$numbernational[] = $nationalRow;
}
}

Due to logic of your code, it must be just
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)
{
$numberlist = $list;
$numbernational = $national;
}

Try something like:
$all = array_merge($list, $national);
foreach($all as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}

Related

re-arrange multidimensional php array

I need to re-arrange a php multidimensional array so that to 'match' corresponding values from different arrays;
this is my reproducible example
<?php
// my original array
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4)
);
print_r($myar);
// my desired result, new array
$myar_new= array(
array('xxx'=>1,'yyy'=>2),
array('xxx'=>3,'yyy'=>4)
);
print_r($myar_new);
?>
any help for that?
thanks
If I got your logic right then this function is what you need.
(Edited)
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
$i = 0;
$groupStart = null;
$collect = [];
while($i < $c) {
$row = current($srcArray[$i]);
if ($row == $groupStart) {
$newArray[] = $collect;
$collect = [];
}
$tmp = array_values($srcArray[$i]);
$collect[] = [$tmp[0] => $tmp[1]];
if ($groupStart === null) $groupStart = $row;
$i++;
}
$newArray[] = $collect;
return $newArray;
}
print_r(strange_reformat($myar));
yes, that's it...
but now I need to generalise it, please consider this case
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'zzz','B'=>5),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4),
array('A'=>'zzz','B'=>6)
);
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
for ($i=0; $i<$c; $i+=3) {
$first = array_values($srcArray[$i]);
$second = array_values($srcArray[$i+1]);
$third = array_values($srcArray[$i+2]);
$newArray[] = [$first[0]=>$first[1], $second[0]=>$second[1], $third[0]=>$third[1]];
}
return $newArray;
}
print_r(strange_reformat($myar));

Find unique (not repeating) combination php

I'm facing a technical problem here, I have an array [PER_DAY, PER_SIZE, PER_TYPE], I want to find combination all of the item without repeating the element, the result should be
[PER_DAY]
[PER_SIZE]
[PER_TYPE]
[PER_DAY, PER_SIZE]
[PER_DAY, PER_TYPE]
[PER_SIZE, PER_TYPE]
[PER_DAY, PER_SIZE, PER_TYPE]
This code repeating same value, so the result is too much.
$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];
function combinations($arr, $level, &$result, $curr=[]) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
This question possible duplicate, but I cannot found example similar like this, thanks.
function pc_array_power_set($array) {
// initialize by adding the empty set
$results = array(array( ));
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return array_filter($results);
}
$set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$power_set = pc_array_power_set($set);
echo '<pre>';
print_r($power_set);
You have make combination from array, will help you :-PHP array combinations

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

PHP push associative array in normal array

I have to push an associative array in a normal array (not to convert).
Example (NO CODE):
project = {}
element["title"] = "My title"
element["description"] = "My description"
is there a way to have this
echo $project->title;
//or
echo $project[0]["title"]
?
I'v tried this, but server says: ERROR 500
$i = 0;
$projects = {};
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}
$projects = {}; is not valid php.
If you want to initialize an empty array (associative or numeric, that does not matter), you need:
$projects = [];
or on older php versions:
$projects = array();
Also note that you need to do the same to your $elements array at the beginning of each iteration otherwise it will grow on every iteration. Assuming that the descriptions are not all the same...
foreach($projectsElements as $element) {
$elements = [];
while($i <= $nRowsForProject) {
...
And your while loop does not seem to make a lot of sense: You are not using the $i variable in your loop so are just doing the same assignments on each iteration.
$projects = []; // declare empty array
foreach($projectsElements as $element) {
$projects []= $element; // push $element into $projects array
}
$i = 0;
$projects = array();
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$elements = array();
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}

php or any program language

Hi anybody can help me to find the maximum value of the array that are given in the below . i expect the result of 650 is the maximum value....
$my_array = array(array(128,300,140)10,15,array(130,array(500,650)));
Here you go, using RecursiveArrayIterator in 3 readable lines of code:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flattenedArray = iterator_to_array($it);
$max = max($flattenedArray);
Or, if you want to not flatten (and copy), but prefer to iterate (uses far less memory, but slower):
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$max = 0;
foreach ($it as $value) {
$max = max($value, $max);
}
Flatten the array, then call max() on it. The return value of max() should be 650 from your example.
Also possible is
$data = array(array(128,300,140),10,15,array(130,array(500,650)));
$max = 0;
array_walk_recursive(
$data,
function($val) use (&$max) {
if($val > $max) $max = $val;
}
);
echo $max; // 650
You could also do it recursively, if the item is an array, call the function again to return the max item from that array.
In the end you should have always the max item and then in the last iteration, you could call the max from those results.
This does the trick:
function flatten($ar) {
$toflat = array($ar);
$res = array();
while (($r = array_shift($toflat)) !== NULL) {
foreach ($r as $v) {
if (is_array($v)) {
$toflat[] = $v;
} else {
$res[] = $v;
}
}
}
return $res;
}
$arr = array(array(128,300,140),10,15,array(130,array(500,650)));
echo max(array_flatten($arr));
EDIT: Updated flatten array with the one at How to "flatten" a multi-dimensional array to simple one in PHP?
<?php
$my_array = array(array(128,300,140),10,15,array(130,array(500,650)));
function findLargest($arr) {
$largest = 0;
foreach ($arr as $item) {
if (is_array($item)) {
$item = findLargest($item);
}
if ($item > $largest) {
$largest = $item;
}
}
return $largest;
}
echo "Largest is ".findLargest($my_array)."\n";
?>
function maximum($in)
{
if (!is_array($in)) $max = $in;
else foreach ($in as $element)
{
$elementMax = maximum($element);
if (isset($max)) $max = max($elementMax, $max); else $max = $elementMax;
}
return $max;
}

Categories