-1
$arr = array (
  
      array(
          'type' => 'Tea', 'amount' => $expense_tea, 'desp' => $expense_tea_desc
      ),
      array(
          'type' => 'BusFare', 'amount' => $expense_bus, 'desp' => $expense_bus_desc
      ),
      array(
          'type' => 'Food', 'amount' => $expense_food, 'desp' => $expense_food_desc
      )
  );
    $myObj1->expensedetails = json_encode($arr);
$json1 = json_encode($myObj1);

Description

  1. I have tried to create a nested json array using php

The Output:

{
    "expensedetails": {
         "[{\"type\":\"Tea\",\"amount\":\"0\",\"desp\":\"0\"},{\"type\":\"BusFare\",\"amount\":\"0\",\"desp\":\"0\"},{\"type\":\"Food\",\"amount\":\"0\",\"desp\":\"0\"}]"
      }
}

Explanation

  1. The json has been converted to string

Expected Output

{
"expensedetails":
        [
    {"type":"Tea","amount":"0","desp":"0"},
    {"type":"BusFare","amount":"0","desp":"0"},
    {"type":"Food","amount":"0","desp":"0"},
    {"type":"SalaryAdvance","amount":"0","desp":"0"},
    {"type":"OT","amount":"0","desp":"0"},
    {"type":"IceFlakes","amount":"0","desp":"0"}
    ]
}

Conclusion

  1. I need a code like in the above-expected code output
  2. But when I tried to do nested json array
Ac. Selvan
  • 41
  • 4
  • What is a `jested json array` – RiggsFolly Oct 12 '22 at 16:51
  • 1
    why you're encoding twice? that's why you're getting data escaped. – OMi Shah Oct 12 '22 at 16:52
  • 1
    remove ``json_encode`` from ``$myObj1->expensedetails = json_encode($arr);`` and asssign directly ``$myObj1->expensedetails = $arr;`` – OMi Shah Oct 12 '22 at 16:53
  • "expensedetails": { "M": { "BusFare": { "S": "50" }, "Food": { "S": "500" }, "FutureUse": { "S": "0" }, "IceFlakes": { "S": "500" }, "OT": { "S": "10" }, "OtherExpenses": { "S": "0" }, "SalaryAdvance": { "S": "0" }, "Tea": { "S": "10" } } } the output is like this this is not the output i needed – Ac. Selvan Oct 12 '22 at 16:57
  • Does this answer your question? [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) – Markus Zeller Oct 12 '22 at 17:07

1 Answers1

2

Your problem is this:

$myObj1->expensedetails = json_encode($arr);

which sets expensedetails to a string that is already encoded as JSON.

If you want it to be a nested array in the JSON, it needs to be a nested array in the PHP - not an already-encoded string. Just do this:

$myObj1->expensedetails = $arr;
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • "expensedetails": [ "M": { "BusFare": { "S": "50" }, "Food": { "S": "500" }, "FutureUse": { "S": "0" }, "IceFlakes": { "S": "500" }, "OT": { "S": "10" }, "OtherExpenses": { "S": "0" }, "SalaryAdvance": { "S": "0" }, "Tea": { "S": "10" } } ] I need the output like this – Ac. Selvan Oct 12 '22 at 17:06