2

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
6
  • googling your question gives the answer in the first result php.net/json_encode Commented Oct 10, 2015 at 17:11
  • i know this function but its not solve my problem because json_encode give just the value read my question again Commented Oct 10, 2015 at 17:12
  • where did array come from? Wouldn't be surprised if you didn't strip out available keys already Commented Oct 10, 2015 at 17:20
  • this array is came from database Commented Oct 10, 2015 at 17:21
  • sorry, i completely missed that you were adding 'name,'price', and 'quantity'. As @charlietfl alluded to, you might be able to use your database library to pull rows out in an associative array. For example, mysqli has this function Commented Oct 10, 2015 at 17:27

1 Answer 1

4

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));
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.