1

Hi guys I'm trying to map key with values in PHP to create JSON object, can someone help please.

My keys array:

[
    "ID",
    "NAME",
    "PRICE",
    "TYPE"
]

My values array:

[
   [
        "1",
        "Chicken Royal",
        "25",
        "Sandwich"
    ],
    [
        "2",
        "Beef Whopper",
        "30",
        "Burger"
    ],
    [
        "3",
        "Beef Royal",
        "30",
        "Burger"
    ]
]

What I'm looking for is:

[
    "ID":"1",
    "NAME":"Chicken Royal",
    "PRICE":"25",
    "TYPE":"Sandwich"
]

I've used this function

$result = array_map( function($k,$v) { return array('column' => $k,'value' => $v); }, array_keys($columnNames),$values);
3
  • And what have you done to try and achieve this, so far? We're not here to do your job for you. Commented Oct 27, 2015 at 18:04
  • @MarcB I've used this function $result = array_map( function($k,$v){ return array('column' => $k,'value' => $v); }, array_keys($columnNames),$values); Commented Oct 27, 2015 at 18:06
  • Welcome on SO nevertheless :-) Commented Oct 27, 2015 at 18:07

1 Answer 1

5

With array_combine you can creates an array by using one array for keys and another for its values.

$keys = [
    "ID",
    "NAME",
    "PRICE",
    "TYPE"
];

$values = [
   [
        "1",
        "Chicken Royal",
        "25",
        "Sandwich"
    ],
    [
        "2",
        "Beef Whopper",
        "30",
        "Burger"
    ],
    [
        "3",
        "Beef Royal",
        "30",
        "Burger"
    ]
];

$results = array_map(function($values) use ($keys) {
    return array_combine($keys, $values);
}, $values);

var_dump($results);

Output:

array(3) {
  [0]=>
  array(4) {
    ["ID"]=>
    string(1) "1"
    ["NAME"]=>
    string(13) "Chicken Royal"
    ["PRICE"]=>
    string(2) "25"
    ["TYPE"]=>
    string(8) "Sandwich"
  }
  [1]=>
  array(4) {
    ["ID"]=>
    string(1) "2"
    ["NAME"]=>
    string(12) "Beef Whopper"
    ["PRICE"]=>
    string(2) "30"
    ["TYPE"]=>
    string(6) "Burger"
  }
  [2]=>
  array(4) {
    ["ID"]=>
    string(1) "3"
    ["NAME"]=>
    string(10) "Beef Royal"
    ["PRICE"]=>
    string(2) "30"
    ["TYPE"]=>
    string(6) "Burger"
  }
}
Sign up to request clarification or add additional context in comments.

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.