-2

i have this type of data store in mysql, how can i echo only the amount value from this?

{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}

this code looks like json data, if yes then should i be using jquery to echo the values or is there a way to do it in php?

2 Answers2

0

You can use the json_decode function to turn it into a PHP object and then access its properties. For your example, you can do this to get the "amount" property:

<?php
$js='{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}';
echo json_decode($js)->{"1"}->amount;
?>
  • is there a way to get all the values of amounts {"1"} {"2"} {"3"} etc – user3647738 Jan 15 '23 at 01:54
  • @user3647738 json_decode($js) make JSON to an array, so you can access all items – Ehsan Jan 15 '23 at 04:03
  • Actually this is what i was trying to do and it worked $json_string = '{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}; $data = json_decode($json_string, TRUE); $total = 0; foreach ($data as $value) { $total += $value['amount']; } echo $total; – user3647738 Jan 15 '23 at 08:12
0
$data = json_decode('{"1":{"amount":"700","date":"2022-10-31","amount_discount":"0","amount_fine":"0","description":"","collected_by":"John Doe","payment_mode":"Cash","received_by":"12","inv_no":1},"2":{"amount":"300","date":"2022-12-17","description":" Paid by: Jane Doe","amount_discount":0,"amount_fine":"0","payment_mode":"upi","received_by":"23","inv_no":2}}');
Ex1: ((array) $data)[1]->amount
Ex2: $data->{'1'}->amount]);
soufiane
  • 1
  • 2