Ashok Kumar Reddy S
Ashok Kumar Reddy S

Reputation: 105

Need help in php JSON conversion

I am trying to convert php array to JSON format, I am not getting as desired, please provide a solution.

I am getting data from database

$banks =   SELECT bankname FROM re_banks.

And I am converting to JSON with below code.

$return_arr = Array();

foreach($banks as $row){
array_push($return_arr,$row);
}
echo json_encode($return_arr);

output is:

[{"bankname":"Allahabad Bank"},{"bankname":"Andhra Bank Ltd"}]

Output I need is :

[{"Allahabad Bank":"Allahabad Bank"},{"Allahabad Bank":"Andhra Bank Ltd"}]

Please help me.

Regards, Ashok

Upvotes: 0

Views: 37

Answers (2)

Justin E
Justin E

Reputation: 1250

foreach($banks as $row){
  $return_arr[$row['bankname']] = $row['bankname'];
}

This will set the key and the value equal to the same text.

Upvotes: 3

Jeff Lambert
Jeff Lambert

Reputation: 24661

Try this:

foreach($banks as $row){
    $return_arr[$row['key']] = $row['key'];
}

echo json_encode($return_arr);

The 'key' you need to supply above is probably 'bankname', but it could also be index 0. That depends on how you're fetching the data from the database.

Upvotes: 2

Related Questions