1

I have the following two things:

  1. $_POST array with posted data
  2. $params array with a path for each param in the desired data array.

    $_POST = array(
    'name'      => 'Marcus',
    'published' => 'Today',
    'url'       => 'http:://example.com',
    'layout'    => 'Some info...',
    );
    
    $params = array(
    'name'      => 'Invoice.name',
    'published' => 'Page.published',
    'url'       => 'Page.Data.url',
    'layout'    => 'Page.Data.layout',
    );
    

I would like to generate the $data array like the example below. How can I do that? Notice how the "paths" from the $params array are used to build the keys for the data array, filling it with the data from the $_POST array.

$data = array(
    'User' => array(
        'name' => 'Marcus',
    ),
    'Page' => array(
        'published' => 'Today',
        'Data' => array(
            'url' => 'http:://example.com',
            'layout' => 'Some info...',
        ),
    ),
);
2
  • What exactly is your problem? Doesn't $data=array(array['User']=$_POST['name']) etc. work? Commented Mar 11, 2013 at 13:20
  • In the specific example, yes, but I want do build the $data array programmatically based on the paths in $params. The above is just an example. The same concept shall be derived on various places. Commented Mar 11, 2013 at 14:13

1 Answer 1

0

I would use referenced variables:

$post = array( // I renamed it
  'name'      => 'Marcus',
  'published' => 'Today',
  'url'       => 'http:://example.com',
  'layout'    => 'Some info...',
);

$params = array(
  'name'      => 'Invoice.name',
  'published' => 'Page.published',
  'url'       => 'Page.Data.url',
  'layout'    => 'Page.Data.layout',
  );

echo '<pre>'; // just for var_dump()
foreach($post as $key=>$var){ // take each $_POST variable
  $param=$params[$key]; // take the scheme fields
  $path=explode('.',$param); // take scheme fields as an array
  $temp=array(); // temporary array to manipulate
  $temp_original=&$temp; // we need this the same as we're going to "forget" temp
  foreach($path as $pathvar){ // take each scheme fields
    $temp=&$temp[$pathvar]; // go deeper
    }
  $temp=$var; // that was the last one, insert it
  var_dump($temp_original); // analize carefully the output
}

All you have to do now is to combine them all, they are not exactly what you want, but this will be easy.

And please note, that each $temp_original fields are pointing at $post variable data! (&string instead of string). You may want to clone it somehow.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.