How to output a PHP array from ajax $_POST and split or explode the values into key and value
Get the solution ↓↓↓I am attempting to take array values sent via $_POST from ajax and use the delimitator as the point to split/explode into a usable variable.
Sample of ajax:
function update_dt_reason() {
$.ajax({
url: "inc/daily.update.dt_reason.php?",
type: "post",
data: $('.dt_reasons:checked').serializeArray(),
success: function(data) {
$('#txtNew').html(data);
}
});
};
Example of PHP:
<?php
$testing = print_r($_POST);
$array = array();
$array = explode('|', $testing);
foreach($array as $key => $testing)
{
$array[$key] = explode('|', $testing);
}
echo "<pre>";
print_r($_POST);
?>
Example Output Array:
Array (
[Well] => Array
(
[0] => 1|5
[1] => 1|3
[2] => 1|1
[3] => 1|6
[4] => 1|7
[5] => 1|2
[6] => 1|4
[7] => 2|1
[8] => 2|6
[9] => 2|7
[10] => 2|4
[11] => 3|5
[12] => 3|1
))
Desired output: Either of the below two:
Array ([0] => 1 => 5)
Array ([1] => 1 => 3)
Array ([2] => 1 => 1) etc.
Or, which would be even better:
Array
(
[0] => 1 => Array
(
[0]=>5
[1]=>3
[2]=>1
[3]=>6
[4]=>7
[5]=>2
...
)
[1] => 2 => Array
(
[0]=>1
[1]=>6
[2]=>1
[3]=>7
[4]=>4
)
[2] => 3 => Array
(
[0]=>5
[1]=>1
)
I can't submit without more information, so I will try to have more, while keeping it relevant. I am using a form with multiple checkboxes that are assigned to ID's in a sql database. They are all listed, and are tied back to the record that will be updated by the check/uncheck of the box. I'm attempting to add a picture for a visual reference.
Answer
Solution:
You have a couple of errors in your PHP script. Try this:
<?php
$testing = print_r($_POST);
$array = array();
// $array = explode('|', $testing); // Remove this line
foreach($_POST['Well'] as $key => $testing) // Loop over the POSTed array
{
$array[$key] = explode('|', $testing);
}
echo "<pre>";
print_r($array); // Print the result, not the input.
?>
Here's a version that produces your preferred format:
<?php
$_POST['Well']=[0=>"1|2", 1=>'3|4', 2=>'1|5'];
$arr = [];
foreach($_POST['Well'] as $val) {
$t = explode("|",$val);
if (!isset($arr, $t[0])) {
$arr[$t[0]] = [];
}
$arr[$t[0]][] = $t[1];
}
print_r($arr);
Output:
Array
(
[1] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 4
)
)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: please make sure the php redis extension is installed and enabled.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.