2

I am using the following code to get two arrays into one json result. But getting only the first index as result. Is there any error in the code or anybody can suggest an alternate method to get the same result.

$array1 = $_POST['array1'];
$array2 = $_POST['array2'];

$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
    $jsonArray[] = array('name' => $name, 'value' => $value);
}

echo $json = json_encode($jsonArray);

$_POST['array1'] = array(4) {
[0]=>
string(3) "day1"
[1]=>
string(3) "day2"
[2]=>
string(3) "day3"
[3]=>
string(3) "day4"
}

$_POST['array2'] = array(4) {
[0]=>
string(3) "item1"
[1]=>
string(3) "item2"
[2]=>
string(3) "item3"
[3]=>
string(3) "item4"
}

Expected result should be like

[{"name":"day1","value":"item1"},{"name":"day2","value":"item2"},{"name":"day3","value":"item3"}]
Jerry Jones
  • 776
  • 1
  • 13
  • 29
  • where is your result? expected output, please? – M.Hemant Mar 04 '19 at 04:59
  • The output you've provided correctly echo's out `[{"name":"size","value":"L"},{"name":"color","value":"Black"}]` (Before you edited it). Check your `$_POST` array and make sure it's the expected values. – Blue Mar 04 '19 at 04:59
  • 1
    It looks like you are expecting a result that would come from array_merge. You might want to check the documentation of array_combine at http://php.net/manual/en/function.array-combine.php – asiby Mar 04 '19 at 05:03
  • What's the result that you expect. Can you mock it up so that we get a visual of what you expect? – asiby Mar 04 '19 at 05:05
  • 1
    Your code works fine https://3v4l.org/J6XXY – Nick Mar 04 '19 at 05:19
  • Another way to combine your array without using `array_combine` https://3v4l.org/fMILF – Ankur Tiwari Mar 04 '19 at 05:57

1 Answers1

0

Try this,

$arr1 = array('0' => 'day1', '1' => 'day2', '2' => 'day3', '3' => 'day4');
echo'<pre>';print_r($arr1);
$arr2 = array('0' => 'item1','1' =>  'item2','2' =>  'item3','3' =>  'item4');
echo'<pre>';print_r($arr2);
echo'<pre>';print_r(array_combine($arr1, $arr2));
 $newArray = array();
  foreach(array_combine($arr1, $arr2) as $key => $value){
      array_push($newArray, array('name'=> $key,'value'=>$value));
  }
echo'<pre>';print_r($newArray);
echo json_encode($newArray);die;
M.Hemant
  • 2,345
  • 1
  • 9
  • 14