1

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"
        }
      ]
    }
1
  • 1
    $arr['prices'] = []; and array_push($arr['prices'], $data); and you are good. Commented Oct 26, 2021 at 12:58

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1
$arr = [];

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

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


print_r(json_encode($arr));

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.