Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to use Json array in the php code. The problem is that I'm in a for loop and need to separate the array in 2 and then want to merge it. but so far it didn't work. I use it to have a graph (jqxChart).

Here is my code

for($i = 0; $i < $nb; $i++){
   if ($i%2 == 1){  
    $time[$i] = (hexdec($hour[$i]));
    $orders1[] = array(
            'OrderDate' => $time[$i],
        );
   }else{ 
    $hour[$i] = $hour[$i] + 1;
    $orders2[] = array(
             'ProductName' => $hour[$i],
    );
  }
}
$orders[] = array_merge_recursive( $orders1[], $orders2[] );

}

echo json_encode($orders);

Thanks

share|improve this question
    
How about just $orders = array_merge($orders1, $orders2)? –  Ja͢ck Aug 13 '13 at 2:47
    
I try this too but it give the same result –  usertfwr Aug 13 '13 at 2:48
    
array_merge_recursive( $orders1[], $orders2[] ); is incorrect. The [] operator after a variable is for assignment. You should only be using the brackets if a = is following the expression. By doing $orders[] = array_merge... You are appending the array merge results to $orders, not assigning them. P.S. sorry for the lack of code styling. I'm on my iPad :-( –  kuujo Aug 13 '13 at 3:21

2 Answers 2

up vote 1 down vote accepted

try this code,

$orders1 = array();   
$orders2 = array();  
for($i = 0; $i < $nb; $i++){
  if ($i%2 == 1){  
    ....
    $temp1 = array(
            'OrderDate' => $time[$i],
        );
    array_push($orders1, $temp1);
   }else{ 
    ....
    $temp2 = array(
             'ProductName' => $hour[$i],
    );
     array_push($orders2, $temp2);
   }
  }
}
$orders = array_merge( $orders1, $orders2 );
echo json_encode($orders);
share|improve this answer

Remove the square brackets. Instead of:

$orders[] = array_merge_recursive($orders1[], $orders2[]);
       ^^                                 ^^          ^^

Just put:

$orders = array_merge($orders1, $orders2);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.