如何获取第一个键(0或关联键)形成数组并在新数组中输出

时间:2019-05-27 02:15:56

标签: php arrays

我想获取此数组的第一个元素并放入新的相同数组输出中

一个要求:不能通过引用索引传递完成,例如0

此输入数组

#include <iostream>

using namespace std;

template <typename... types>
void print(types... Params){
    std::cout << "number of elements: " << sizeof...(Params) << " ";
    ((std::cout << Params), ...);
}

int main(){
  print(123, 456);
}

我需要的新阵列

这是OutPUT阵列

... function search($name)
{
$patterns[0] = '/[á|â|à|å|ä]/';
$patterns[1] = '/[ð|é|ê|è|ë]/';
$patterns[2] = '/[í|î|ì|ï]/';
$patterns[3] = '/[ó|ô|ò|ø|õ|ö]/';
$patterns[4] = '/[ú|û|ù|ü]/';
$patterns[5] = '/æ/';
$patterns[6] = '/ç/';
$patterns[7] = '/ß/';
$replacements[0] = 'a';
$replacements[1] = 'e';
$replacements[2] = 'i';
$replacements[3] = 'o';
$replacements[4] = 'u';
$replacements[5] = 'ae';
$replacements[6] = 'c';
$replacements[7] = 'ss';
return preg_replace($patterns, $replacements, $name);
...

注意 我可以控制输入数组相同,我尝试使用php中的foreach和Laravel Helper函数头中的Tray,让我得到S

        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']

array:6 [▼
  0 => array:3 [▼
        0 => "id"
        1 => "ID"
        2 => "dt-text"
  ]
  1 => array:3 [▼
        0 => "name"
        1 => "Name"
        2 => "dt-text"
  ]
  2 => array:3 [▼
        "artistList" => array:3 [▼
              0 => "list"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Artist List"
        1 => "dt-select"
  ]
  3 => array:3 [▼
        "nationality" => array:3 [▼
              0 => "nationality"
              1 => "mm"
              2 => "defalut"
        ]
        0 => "Nationality"
        1 => "dt-select"
  ]
  4 => array:3 [▼
        0 => "view"
        1 => "View"
        2 => ""
  ]
  5 => array:3 [▼
        0 => "status"
        1 => "Status"
        2 => ""
  ]
]

让我无法获得Resslut,我该怎么办?

1 个答案:

答案 0 :(得分:2)

由于您要更改数组的键(结构),因此无法生成新数组或通过引用传递数组而无法做到这一点。通过生成新数组的一种方法是使用array_reduce

$array = [
        [ 'id','ID','dt-text' ] ,
        [ 'name','Name','dt-text' ] ,
        [ 'artistList'=>['list','mm','defalut']  ,'Artist List','dt-select'] ,
        [ 'nationality'=>['nationality','mm','defalut']  ,'Nationality','dt-select'] ,
        [ 'view','View',''],
        [ 'status','Status' ,'']
    ];
$array = array_reduce($array, function ($c, $v) { 
    $first_key = array_keys($v)[0];
    return array_merge($c, array($first_key => $v[$first_key])); }, []);
print_r($array);

输出:

Array (
  [0] => id
  [1] => name
  [artistList] => Array (
    [0] => list
    [1] => mm
    [2] => defalut
  )
  [nationality] => Array (
    [0] => nationality
    [1] => mm
    [2] => defalut
  )
  [2] => view
  [3] => status
)

Demo on 3v4l.org