0

I have below two arrays,

$category = array('available', 'notavailable' );
$values = array(1, 2 );

Now i want to get JSON output as below,

[{category: 'available', value:1}{category: 'notavailable', value:2}]

I tried using array_merge array_combine but could not got desired outlut with new Key values category and value,

How can i get that?

Thanks,

1
  • 1
    Take a look at array_map() to combine both arrays into the desired output which you then can encode. Commented Jun 7, 2016 at 16:22

2 Answers 2

1

You can use array_map, if you have fixed keys:

<?php

$category = array('available', 'notavailable' );
$values = array(1, 2 );

$array = array_map(function($category, $value) {
    return ['category' => $category, 'value'=>$value];
}, $category, $values);

echo "<pre>";
var_dump(json_encode($array));
echo "</pre>";

Output:

string(74) "[{"category":"available","value":1},{"category":"notavailable","value":2}]"
Sign up to request clarification or add additional context in comments.

Comments

0

I think you must doing like this:

$result = array();
for ($i = 0; $i < count($category); $i++) {
    $result[] = array(
       'category' => $category[$i],
       'value' => $values[$i]
    );
}

echo json_encode($result);

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.