0

Good Day!

Any suggestions on how can I merged and print 3 arrays in PHP. I retrieved data from database and put it in ARRAY.

1st Array: $date[] = $row['date'];

2nd Array: $requestor[] = $row['requestor'];

3rd Array: $die[] = $row['die'];

then I use foreach to print the retrieved data stored from each Array that meets the condition.

foreach($date as $item_date){ 
  echo $item_date;
}

foreach($requestor as $item_requestor){ 
  echo $item_date;
}

foreach($die as $item_die){ 
  echo $item_requestor;
}

But the result of this code is like this:

date1
date2
date3
requestor1
requestor2
requestor3
die1
die2
die3

My goal is this one:

date1 - requestor1 - die1
date2 - requestor2 - die2
date3 - requestor3 - die3

Any Idea oon how can I achieved this output.

TIA

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87

5 Answers5

1

You have to do it manually count on loop like this

$count = count($date)-1;

then loop through this

for ( $i=0;$i <= $count; $i++ ) {
   $arrayGenerate[$i] = array(
        'row1' => $data[$i].'-'.$requestor[$i].'-'.$die[$i]
   );
}

like this

Agha Umair Ahmed
  • 1,037
  • 7
  • 12
0

Try with -

for($i = 0; $i <= count($date); $i ++) {
    echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

Assuming the all 3 arrays count/size is same & you want it in this fashion

<?php
    $a = array('1','2','3');
    $b = array('4','5','6');
    $c = array('7','8','9');

    for($i=0;$i<count($a);$i++)
    {
        echo $merged_arr_str = $a[$i] . " - " . $b[$i] . " - ". $c[$i] . " <br/>"; 
    }
?>
Rohit Batra
  • 674
  • 4
  • 18
0

You can try this

Example One:-

$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');

$count = max(count($date), count($requestor), count($die));
$newarray = array();
for($i=0; $i < $count; $i++) {
   //Demo1
   if (isset($date[$i])) $newarray[] = $date[$i];
   if (isset($requestor[$i])) $newarray[] = $requestor[$i];
   if (isset($die[$i])) $newarray[] = $die[$i];

   //Demo2
   //echo $ouput = $date[$i].'-'.$requestor[$i].'-'.$die[$i];
}
//array merge output
var_dump($newarray);

Example Two

$date = array('date1','date2','date3','date4');
$requestor = array('requestor1','requestor2','requestor3','requestor4');
$die = array('die1','die2','die3','die4');
$arrays = array($date, $requestor, $die);
array_unshift($arrays, null);
$n = call_user_func_array('array_merge', call_user_func_array('array_map', $arrays));
print_r($n);
GIPSSTAR
  • 2,050
  • 1
  • 25
  • 20
0
for($i = 0; $i < count($date); $i ++) {
        echo $date[$i]." - ".$requestor[$i]." - ".$die[$i];
    }

this loop will iterat untill last element of date array.if you want to put equal to sign then you have to initialize $i with 1.

exm. if $i = 0 then $i < count($date) 
                OR
     if $i = 1 then $i <= count($date)  
Yogesh
  • 727
  • 2
  • 7
  • 19