Abomusab Revo
Abomusab Revo

Reputation: 78

convert array to json object in php

Hi i have an array and i need to convert this array to json object

but i need to define a key for each element like my example in the bottom.

my array is:

$arr= array(["Soap", "25", "10"],["Bag", "100", "15"],["Pen", "15", "13"]);

what i expect is something like this object to use it in angular

{ "payment":[
{'Name': "Soap",  'Price': "25",  'Quantity': "10"},
{'Name': "Bag",   'Price': "100", 'Quantity': "15"},
{'Name': "Pen",   'Price': "15",  'Quantity': "13"}

]  } 

how can i do that with php

json_encode is not solve my problem

Upvotes: 2

Views: 3954

Answers (1)

FuzzyTree
FuzzyTree

Reputation: 32402

You'll need to create an associative array

$payment = array();

foreach($arr as $row) {
    $payment[] = array(
        'Name' => $row[0],
        'Price' => $row[1],
        'Quantity' => $row[2],
    );
}

print json_encode(array('payment' => $payment));

Upvotes: 4

Related Questions