1

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

3
  • How about just $orders = array_merge($orders1, $orders2)? Commented Aug 13, 2013 at 2:47
  • I try this too but it give the same result Commented Aug 13, 2013 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 :-( Commented Aug 13, 2013 at 3:21

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

Remove the square brackets. Instead of:

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

Just put:

$orders = array_merge($orders1, $orders2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.