2

I have some inputs that I need to process from a form. The # of inputs from a form depends on the number of languages in my application. For example, lets say I support english and french:

$input = array(
  'name_1' => 'Some input in english',
  'content_1' => 'Some long text in english',
  'name_2' => 'Some input in french',
  'content_2' => 'Some long text in french'
);

...Where '1' and '2' are the IDs of english and french respectively. What I want to do is explode the strings:

foreach($input as $key=>$val)
{
  $exploded = explode('_', $key);
  $arr = $exploded[1];
  $key = $exploded[2];
}

..And then push them to separate arrays. Keep in mind that there could be 2 languages, or 10, so just initializing 2 arrays and checking for '1' or '2' as the $key won't work.

How can I push the values of each to an array so that I end up with an array that look something like this?

$results = array( '1' => array('name' => 'Some input in english', 'content' => 'Some long text in english'), '2' => array('name' => 'Some input in french', 'content' => 'Some long text in french');

Thanks in advance. One idea I had was to initialize 2 arrays based off a count of unique key values, but wanted to check first to see if there is a "right" way to do this for a function already there for something like this.

1 Answer 1

3

Would something like this work for you?

$results = array();
foreach($input as $key=>$val)
{
  $exploded = explode('_', $key);
  $results[$exploded[1]][$exploded[0]] = $val;
}
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.