Reputation: 241
I've got an array, called $data which needs to be updated with data from an ajax call.
There are two variables sent via an ajax call (with example inputs):
sectionDetails:
[111][0][2][0][service_providers][]
serviceProvider:
Google
The serviceProvider is the data, and the sectionDetails is the array in which the serviceProvider should be in, in the $data array.
What I need is the $data array to end up as:
$data = Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] = Google
)
)
)
)
)
)
This way, I can dynamically input data into any cell and then later I can update specific arrays (e.g. $data[111][0][2][0][service_providers][0]
= "Yahoo"
;
The $_POST['sectionDetails']
is however a string which is where the issue is.
Is there a way to change this string to an array that can then be appended to the main $data array (and in the case of an existing value in the same section, update the value)?
Hope that makes sense.
Upvotes: 4
Views: 89
Reputation: 3848
Being very careful and depending on the situation, you could use eval
:
eval("\$data$sectionDetails = '$serviceProvider';");
print_r($data)
will return:
Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] => Google
)
)
)
)
)
)
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
Upvotes: 1
Reputation: 138
If you create a function like this:
function setToPath(&$data, $path, $value){
//$temp will take us deeper into the nested path
$temp = &$data;
//notice this preg_split logic is specific to your path syntax
$exploded = preg_split("/\]\[/", rtrim(ltrim($path,"["),"]"));
// Where $path = '[111][0][2][0][service_providers][]';
// $exploded =
// Array
// (
// [0] => 111
// [1] => 0
// [2] => 2
// [3] => 0
// [4] => service_providers
// [5] =>
// )
foreach($exploded as $key) {
if ($key != null) {
$temp = &$temp[$key];
} else if(!is_array($temp)) {
//if there's no key, i.e. '[]' create a new array
$temp = array();
}
}
//if the last index was '[]', this means push into the array
if($key == null) {
array_push($temp,$value);
} else {
$temp = $value;
}
unset($temp);
}
You can use it like this:
setToPath($data, $_POST['sectionDetails'], $_POST['serviceProvider']);
print_r($data)
will return:
Array
(
[111] => Array
(
[0] => Array
(
[2] => Array
(
[0] => Array
(
[service_providers] => Array
(
[0] => Google
)
)
)
)
)
)
Upvotes: 3