3

I have the following key/value from my $_POST variable:

Array
(
     'translations_0_comment' => 'Greetings from UK'
)

What I would like is to set this values to the following array

$data[translations][0][comment] = 'Greetings from UK';

So the idea is that I can have anything in my KEY values, and from that I will populate an array.

Is there any safe way to do this without using eval() ?

All help is appreciated.

UPDATE:

this would be the idea with eval()

foreach ($_POST as $key => $dataValue) {            
    $a = explode("_", $key);
    $builder = '$object';
    foreach ($a as $value) {
        $builder.='['.$value.']';
    }
    $builder.=' = '.$dataValue.';';
    eval($builder);         
}
2
  • 1
    Just curious: how would eval() help anyway? Commented Jun 6, 2012 at 8:59
  • 2
    @Álvaro G. Vicario, just updated my answer Commented Jun 6, 2012 at 9:04

5 Answers 5

5

I think you are looking for this

function set_value($object, $paths, $value, $index){

    $key = $paths[$index];

    $sub_object = $object[$key];
    if (!is_array($sub_object)){
        $object[$key] = $value;
    }else{
        $index = $index+1;
        $object[$key] = set_value($sub_object, $paths, $value, $index);
    }
    return $object;
}
Sign up to request clarification or add additional context in comments.

Comments

1

explode() is what you need:

$data = array();
foreach ($postData as $key => $val) {
    $explodedKey = explode('_', $key);
    $data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}

No need to use eval().

1 Comment

Hm... but I can have have any number of _ in the KEY, so it is not limited to 3.
1

I think this is what you are looking for

Example

In your form which generate the $_POST data rename the input attribute as follows

<input name="data[translations][0][comment]" />

and now your $_POST['data'] will be an array

Comments

0
$data = array();
foreach ($_POST as $keys => $val) {
    $keys_list = explode('_', $keys);
    $link = &$data;
    foreach ($keys_list as $key) {
        $link[$key] = $val;
        $link = &$link[$key];
    }
}

Comments

0

Try this one sir.

$array = array
(
     'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);

$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);

$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
    $start .= "array(\"".$array1[$i]."\" => ";
    $end .=")";
} 
$start = $start ."\"".$arrValue[0]."\"".$end;

eval("\$arr = $start;");

print_r($arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.