如何解析这个数组

时间:2015-11-29 00:22:55

标签: php

我想解析这个数组:

[
'field__i_dont_need' => 'foo',
'another_field_i_dont_need' => 'bar',
'user_name_1' => 'John',
'user_email_1' => 'john@gmail.com',
'user_name_2' => 'Jane',
'user_email_2' => 'jane@gmail.com'
]

$users = [
   0 => [
    'name' => 'John',
    'email' => 'john@gmail.com'
   ],
   1 => [
    'name' => 'Jane',
    'email' => 'jane@gmail.com'
   ]
]

我想我可能需要一些正则表达式魔法,但我不确定。

3 个答案:

答案 0 :(得分:1)

使用array_values()

 $arr = ['user_name_1' => 'John','user_email_1' => 'john@gmail.com','user_name_2' => 'Jane','user_email_2' => 'jane@gmail.com']
 $new_arr = array_values($arr);

 $j=0;
 $final = array();
 for($i=0;$i<count($arr)/2;$i++) {
     $final[$i]['name'] = $new_arr[$j];
     $j++;

     $final[$i]['email'] = $new_arr[$j];
     $j++;
 }

答案 1 :(得分:0)

怎么样

$outarray = [];
foreach ( $inarray as $k => $v )
    if ( preg_match( "/^user_(name|email)_(\d+)$/", $k, $m ) )
        $outarray[ $m[2] ][ $m[1] ] = $v;

它会在1中产生密钥2$outarray,而不是01,但$outarray = array_values( $outarray )会解决这个问题。

答案 2 :(得分:0)

我认为您可以使用以下内容。即使它们位于阵列中的不同位置,它也适用于任意数量的字段。

$data = [
    'field__i_dont_need' => 'foo',
    'another_field_i_dont_need' => 'bar',
    'user_name_1' => 'John',
    'user_email_1' => 'john@gmail.com',
    'user_name_2' => 'Jane',
    'user_email_2' => 'jane@gmail.com'
];

$temp = array();
//Take only the fields you need and their transformed key names
$fields = array(
    'user_name_'=>'name', 
    'user_email_'=>'email'
    );
$i = 0;

foreach($data as $key => $value) { //For all initial data
    foreach($fields as $s_key => $s_value) { //For all your field names you want
        if (strpos($key, $s_key) !== false) { //If it is a field name you want
            $t = explode($s_key, $key); //Explode to take its values
            if (!empty($t[1])) {
                if (empty($temp[$i])) {
                    $temp[$i][$s_value] = $value;
                } else {
                    $temp[$i][$s_value] = $value;
                    $i++;
                }
            }
        }
    }
}

var_dump($temp);

<强>结果:

array (size=2)
  0 => 
    array (size=2)
      'name' => string 'John' (length=4)
      'email' => string 'john@gmail.com' (length=14)
  1 => 
    array (size=2)
      'name' => string 'Jane' (length=4)
      'email' => string 'jane@gmail.com' (length=14)