Home > Software design >  make array instead string in php
make array instead string in php

Time:10-30

ajax call with this data variable gives expected POST data in the controller(server)

Javascript:
var data = "item[]=9&item[]=1&item[]=2&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8"
$.ajax({
    data: data,
    type: 'POST',
    url: '/api/call'
});

Controller:
array:1 [
  "item" => array:9 [
    0 => "1"
    1 => "2"
    2 => "4"
    3 => "3"
    4 => "5"
    5 => "6"
    6 => "7"
    7 => "8"
    8 => "9"
  ]
]

in my requirement, I create a new variable

Javascript:
var data = "item[]=9&item[]=1&item[]=2&item[]=3&item[]=4&item[]=5&item[]=6&item[]=7&item[]=8"
var = other_parameters => [
      "host" => "host name"
      "session" => "current session"
      "timestamp" => "time stamp"
]

let requestData = {
     other_parameters,
     data
}

$.ajax({
    data: requestData,
    type: 'POST',
    url: '/api/call'
});

Controller(Currently I get this data in the controller):
array:2 [
  "other_parameters" => array:3 [
      "host" => "host name"
      "session" => "current session"
      "timestamp" => "time stamp"
  ]
  "data" => "item[]=1&item[]=2&item[]=3&item[]=5&item[]=4&item[]=6&item[]=7&item[]=8&item[]=9"
]

Expected:
array:2 [
    "other_parameters" => array:3 [
        "host" => "host name"
        "session" => "current session"
        "timestamp" => "time stamp"
    ],
    "data" => [
        "item" => array:9 [
            0 => "1"
            1 => "2"
            2 => "4"
            3 => "3"
            4 => "5"
            5 => "6"
            6 => "7"
            7 => "8"
            8 => "9"
        ]
    ]
]

Please help to get expected data in Controller(Server)

CodePudding user response:

You could try and use parse_str, REF: https://www.php.net/manual/en/function.parse-str.php

Example:

$str = 'item[]=1&item[]=2&item[]=3&item[]=5&item[]=4&item[]=6&item[]=7&item[]=8&item[]=9'
parse_str($str, $output);
var_dump($output);

// Output
array:1 [▼
  "item" => array:9 [▼
    0 => "1"
    1 => "2"
    2 => "3"
    3 => "5"
    4 => "4"
    5 => "6"
    6 => "7"
    7 => "8"
    8 => "9"
  ]
]

It should get you to where you need to be.

Edit:

A better way would probably be to convert all your data into a JSON array first and send that. Then just use json_decode to get your array in PHP.

  • Related