1

I have these two arrays.

$arr1 = array(
   [0] => "ABC",
   [1] => "DEF",
   [2] => "GHI",
);

$arr2 = array(
   [0] => 'Y',
   [1] => 'N',
   [2] => 'Y',
);

And I want to convert these arrays into one JSON object array like below.

[ 
  { "contents" : "ABC", "open": "Y" },
  { "contents" : "DEF", "open": "N" },
  { "contents" : "GHI", "open": "Y" },
]

I googled it and it suggested me using the json_encode function, but it didn't give me the result I wanted.

1
  • 1
    Show the code that you tried. Commented Aug 18, 2020 at 7:44

2 Answers 2

2

Simple as:

$newArray = [];
foreach ($arr1 as $key => $value) {
    $newArray[] = ['contents' => $value, 'open' => $arr2[$key]];
}
echo json_encode($newArray);
Sign up to request clarification or add additional context in comments.

Comments

2

glad to help!

I think you've used json_encode in a wrong way.

Please try my code below:

$arr1 = array(
   [0] => "ABC",
   [1] => "DEF",
   [2] => "GHI",
);

$arr2 = array(
   [0] => 'Y',
   [1] => 'N',
   [2] => 'Y',
);

$json_tmp = [];
for ( $i=0; $i<sizeof($arr1); $i++) {
    $json_tmp = ['contents' => $arr1[$i], 'open' => $arr2[$i]];
}

echo json_encode($json_tmp);

Wish you a good day:)

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.