Home > Back-end >  Convert multiple input value to json array on Php?
Convert multiple input value to json array on Php?

Time:11-28

I'm trying to convert multiple input values to json array using php.

Form:

<input name="title[]">
<input name="description[]">
<input name="total[]">

What i'm trying to get:

{"results":
 [{"title", "description", "total" }],
 [{"title", "description", "total" }],
 [{"title", "description", "total" }],
 [{"title", "description", "total" }]
}

Php Code:

$itemCount = count($_POST["title"]);
$_POST['results'] = [];

for($i=0;$i<$itemCount;$i  ) {
    if(!empty($_POST["title"][$i]) || !empty($_POST["description"][$i]) || !empty($_POST["total"][$i])) {
        $_POST['results'] = json_encode([
            [
                'title' => cleardata($_POST["title"][$i]),
                'description' => cleardata($_POST['description'][$i]),
                'total' => cleardata($_POST['total'][$i])
            ],
        ]);
    }
}

print_r(json_encode($_POST['results']));

CodePudding user response:

Your form isn’t clear. I’ll assume it is a set of inputs, each title matching with exactly one description and exactly one total fields.

Also, the JSON you expect is not valid.

We’re making new arrays with elements with the same index in each posted array. You can eventually cast them to Object. We combine them in a global array and parse it to JSON thanks to json_encode().

// Since you didn’t indicate form method
$titleData = $_POST['title'] ?? $_GET['title'];
$descriptionData = $_POST['description'] ?? $_GET['description'];
$totalData = $_POST['total'] ?? $_GET['total'];

$results = [];

foreach ($titleData as $count => $result) {
    $results[] = [$result, $descriptionData[$count], $totalData[$count]];
    // You may cast the added array with (object) if you expect an object
    // rather than an array.
}

return json_encode( ["results" => $results] );
  • Related