开发者

PHP - Creating Arrays by Exploded Strings

开发者 https://www.devze.com 2023-03-14 12:32 出处:网络
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:

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 j开发者_如何学Goust 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.


Would something like this work for you?

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

精彩评论

暂无评论...
验证码 换一张
取 消