Use one foreach loop instead of two - php

I have one array
$array = array(0=>array('id'=>1 ,'va'=>2),1=>array('id'=>3,'va'=>4));
With the help of two foreach() loop i can use it.
foreach($array as $temp)
{
foreach($temp as $key=>$val)
{
echo $key.'=>'.$val;
}
}
As array has more than 5 lacs record. this solution is not feasible for me.
Keys are dynamic so i can not put keys as static inside first for each loop.
I tried following code but till now did not get any solution.
function myfunction($value,$key)
{
foreach($value as $k=>$a)
{
echo $k.'=>'.$a;
}
}
$array = array(0=>array('id'=>1,'va'=>2),1=>array('id'=>2,'va'=>2));
array_walk($array,"myfunction");
And this one also
$keys = Array_keys($array['0']);
for($i=0;$<=count($array);$i++)
{
for($j=0;$j<count($keys);$j++)
{
echo $keys[$j].'=>'.$array[$i][$keys];
}
}
I want to make this code as optmize as possible.

Related

fetching two type of json files with different beginning of structure

I'm processing json file with php with little difference in the beginning of the file ,my problem now is that i built two foreach loops and i am looking for a way to make it one loop.
{"code":0,"rid":"0","data":{"subid":"9174906486819979969","data":{"more":
{"code":0,"rid":"0","data":{"9174906486819979969":{"more":
Now I'm doing like that and it double the code for processing , the rest of the json file is all the same.
foreach($json['data']['data'])
{
}
foreach($json['data'])
{
}
What i need is one foreach loop instead of 2, is that possible?
You can check for the key and if present use it, if not then get the first key:
if(isset($json['data']['data'])) {
$data = $json['data']['data'];
} else {
$data = reset($json['data']); //or current()
}
Or shorter:
$data = $json['data']['data'] ?? reset($json['data']);
Then:
foreach($data as $values) {
//code
}
Another option would be to loop and check for an array, depending on the structure you have:
foreach($json['data'] as $values) {
if(is_array($values)) {
foreach($values as $v) {
//code
}
}

PHP - using a recursive function to find the max() of nested arrays

The following code uses a simple strategy for finding the max of the nested array. It uses foreach to find and label the max value, however, if I got an array that was nested to MORE than two levels, than my code would be useless. Can anyone please explain to me the idea of a function calling itself for it to find unlimited nested arrays? Would be much appreciated.
Here is my code for example:
<?php
$arr = array("1", "2", array("3", "4"));
foreach($arr as $value){
if(is_array($value)){
foreach($value as $value2){
$max_array=array($value);
// no deeper levels
}
} else {
$max_array=array($value);
}
}
echo max($max_array);
?>
You can use array_walk_recursive() for it:
function array_max_recursive($arr)
{
$max = -INF;
array_walk_recursive($arr, function($item) use (&$max) {
if ($item > $max) {
$max = $item;
}
});
return $max;
}
echo array_max_recursive(["1", "2", ["3", "4"]]); // 4
What you want is a recursive function.
The function looks up the biggest element in a an array. If an item in the array is an array, it will find the biggest item in that array and use that to compare.
To find the biggest value in that array it will use the same function.
function findMax($arr){
$max = 0;
foreach($arr as $item){
if(is_array($item)){
$val = findMax($item);
}else{
$val = $item;
}
$max = $val>$max?$val:$max;
}
return $max;
}
Use example:
$arr = Array(1,2,Array(3,10,Array(6,7)));
$arr2 = Array(1,2,Array(3,5,Array(6,7)));
echo findMax($arr)."\n".findMax($arr2);
Result:
10
7

iterate through array, number of keys is variable, the first value being processed differently

Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)

PHP arrays - a 'set where key=?' type function?

Is there a built in php function that allows me to set a value of an array based on a matching key? Maybe i've been writing too much SQL lately, but i wish I could perform the following logic without writing out nested foreach array like the following:
foreach($array1 AS $k1 => $a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$array[$k1]['new_key'] = $a2['value'];
}
}
}
Is there a better way to do this? In SQL logic, it would be "SET array1.new_key = x WHERE array1.id = array2.id". Again, i've been writing too much SQL lately :S
When I need to do this, I use a function to first map the values of one array by id:
function convertArrayToMap(&$list, $attribute='id') {
$result = array();
foreach ($list as &$item) {
if (is_array($item) && array_key_exists($attribute, $item)) {
$result[$item[$attribute]] = &$item;
}
}
return $result;
}
$map = convertArrayToMap($array1);
Then iterate through the other array and assign the values:
foreach ($array2 AS $a2) {
$id = $a2['id'];
$map[$id]['new_key'] = $a2['value'];
}
This are less loops overall even for one pass, and it's convenient for further operations in the future.
This one is fine and correct
foreach(&$array1 AS &$a1) {
foreach($array2 AS $a2) {
if($a1['id'] == $a2['id']) {
$a1['new_key'] = $a2['value'];
}
}
}

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Categories