Jump to content

Creating array in loop and getting result problem


SUNIL16

Recommended Posts

Hi friends,

 

below is my code

$arr1 = array('a'=>'1');
  $arr2 = array('a'=>'0.5');
  $arr3 = array('b'=>'1');
  $arr4 = array('a'=>'1.5');
  $arr5 = array('c'=>'1');
  $arr6 = array('b'=>'1');
  $arr7 = array('c'=>'1.5');
  $arr8 = array('a'=>'1');
  
  $all_array = array_merge_recursive($arr1, $arr2, $arr3, $arr4, $arr5, $arr6, $arr7, $arr8);
  echo "<pre>";
  print_r($all_array);
  echo "</pre>";
  
  foreach($all_array as $all_array_key => $all_array_value)
  {
      $all_count = 0;  
      foreach($all_array_value as $all_array_value_key => $all_array_value_value)
      {
          $all_count += $all_array_value_value;
      }
       
    echo $all_array_key." = ".$all_count."<br>";
  }
  

 

 

now result i am getting

a = 4

b = 2

c = 2.5

 

but my condition is not this i will be creating multiple array using loop, then how can use array_merge_recursive?

 

I want for this above result

 

for($i = 0; $i<$num ; $i++)

{

$arr.$i = array('a'=>'1');//like this i will be sending value dynamically

//(say second will be array('b'=>'1.5') 3rd array('c'=>'1'), 4th array('a'=>'1.5') like that

}

 

then it will create arrays untill that $num value reaches,

 

now how can i get the result in the same way as above.

 

Please let me know any logic or code. how to do this.

 

Instead of doing "$arr.$i", which actually should be written as ${'arr'.$i}, you need to do something like

<?php
$arr = array();
for ($i = 0; $i < $num; ++$i) {
    if (!is_array($arr[$i])) {
         $arr[$i] = array();
    }
    if (!is_array($arr[$i][$result['type'])) {
        $arr[$i][$result['type']] = array();
    }
    $arr[$i][$result['type']][] = $result['value'];
}
?>

 

Note: untested.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.