rjcode rjcode - 5 months ago 13
JSON Question

creating new php array from two arrays by adding new keys values

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,

Answer

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}]"
Comments