Im struggling with a multidimensionnal array while building a form using ajax and PHP. My ajax send a multidimensionnal array to php. And i want to convert this array to a single dimensionnal one.
so considering this code:
$reasons = $_POST['reasons'];
var_dump($reasons);
which output this:
array(1) {
[0]=>
array(2) {
["id"]=>
string(2) "37"
["reason"]=>
string(9) "Something"
}
}
I now want it to be like this:
$reasons = {
37 => "Something"
}
How can i do that ? I have searched for hours and didn't find the right solution to do it...
What i have tried:
1)
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$reasons = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$reasons = array_merge($reasons, array_flatten($value));
} else {
$reasons[$key] = $value;
}
}
return $reasons;
}
array_flatten($_POST['reasons']);
var_dump($reasons);
Output: NULL
$reasons = $_POST['reasons'];
$tabReasons = array_reduce($reasons, 'array_merge', array());
var_dump($tabReasons);
Output this:
array(2) {
["id"]=>
string(2) "37"
["reason"]=>
string(9) "Parce que"
}
Which kind of work but my multidimenssional array can store multiple ID and Reasons. And when that happens, the code above only returns me a single pair of key & value
Like if i have two id and two reasons in my multidimenssional, it will only return me last id and reason into a single array...
i want something like : array(id => reason, id => reason, etc...)