populate array with string received post method

-1

I have a script in javascript, that when executing it sends me this information by post:

array(1) {  ["data"]=>  string(36) "[name:jorge,apellido:nieves,edad:31]"}

but I do not know how to capture it and populate an array:

$info=[];
foreach($_POST['data'] as $key => $value){
    $info[$key]=$value;
}
    
asked by Francisco Núñez 30.10.2017 в 22:44
source

2 answers

2

You will not be able to populate the array because you are iterating a string:

string(36) "[name:jorge,apellido:nieves,edad:31]"

Edit the way you send the information by javascript , it will make the php code work, I'll assume you use ajax:

$.post( url, { data: { name: 'jorge', apellido: 'nieves', edad: '31' } } );

In this way the variable $_POST['data'] will have the following value:

array(3) { ["nombre"]=> string(5) "jorge", ["apellido"]=> string(6) "nieves", ["edad"]=> string(2) "31"}

    
answered by 30.10.2017 в 23:41
0

I guess the error is that it is not able to traverse the array $_POST . This can happen because you have not loaded the variable $_POST .

Let me explain, if you do not use any PHP framework, that is, you use native PHP, the $_POST, $_GET, ... array is not automatically loaded into the controller. Actually the content of these arrays is inside the $GLOBALS array that contains the global variables of your PHP file.

The code for the loop to work would be as follows:

$info=[];
$_POST = $GLOBALS['_POST'];

foreach($_POST['data'] as $key => $value){
    $info[$key]=$value;
}
    
answered by 30.10.2017 в 23:29