Home > Software engineering >  How to add data to the array correctly
How to add data to the array correctly

Time:10-27

Help me how to add data to the array correctly.Below I give an example of what I want to get in the end after printing the array

$arr = [];

    $data = [
        "offer_id" => (string)777380,
        "price" => (string)5633
    ];
    
    array_push($arr, $data);


print_r(json_encode($arr));

I want to get this

    {
      "prices": [
        {
          "offer_id": "777380",
          "price": "5633"
        },
        {
          "offer_id": "777380",
          "price": "5633"
        }
      ]
    }

CodePudding user response:

You can use like below:

    $arr['prices']=[];

    $data = [
        "offer_id" => (string)777380,
        "price" => (string)5633
    ];
    
    array_push($arr['prices'], $data);

    $data = [
      "offer_id" => (string)777380,
      "price" => (string)5633
  ];
  
  array_push($arr['prices'], $data);


print_r(json_encode($arr));

CodePudding user response:

$arr = [];

$data = [
    "offer_id" => (string)777380,
    "price" => (string)5633
];

$arr['prices'][] = $data;


print_r(json_encode($arr));
  •  Tags:  
  • php
  • Related