PHP - 仅使用现有数组中的选定键创建新数组

时间:2017-10-20 06:56:34

标签: php arrays

从PHP中的数组中仅获取所选键及其值的最简单方法是什么? 例如,如果我有一个数组:

$meta = [
      "nickname" => [
        0 => "John"
      ]
      "first_name" =>  [
        0 => "John"
      ]
      "last_name" => [
        0 => "Doe"
      ]
      "description" => array:1 [
        0 => ""
      ]
      "rich_editing" => [
        0 => "true"
      ]
      "comment_shortcuts" => [
        0 => "false"
      ]
      "admin_color" => [
        0 => "fresh"
      ]
      "use_ssl" => array:1 [
        0 => "0"
      ]
      "show_admin_bar_front" => [
        0 => "true"
      ]
      "locale" => [
        0 => ""
      ]
      "wp_capabilities" => [
        0 => "a:1:{s:10:"subscriber";b:1;}"
      ]
      "wp_user_level" => [
        0 => "0"
      ]
      "dismissed_wp_pointers" => [
        0 => ""
      ]
      "department" => [
        0 => "Administrasjon"
      ]
      "region" => [
        0 => "Oslo"
      ]
      "industry" => [
        0 => "Bane"
      ]
    ]

获取仅包含选定键的新数组的最简单方法是什么,例如nicknamefirst_namelast_name等?

2 个答案:

答案 0 :(得分:5)

使用array_flip()array_intersect_key()

Dim dgvComboBox As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
    dgvComboBox.HeaderText = "Select Data"
    dgvComboBox.Name = "dgvComboBox"
    dgvComboBox.Items.AddRange(New Object() {"Value 1", "Value 2", "Value 3"})
    dtgLineMaster.Columns.Add(dgvComboBox)

答案 1 :(得分:1)

试试这个;

$newArray = array();
$newArray['nickname'] = $meta['nickname'];
$newArray['first_name'] = $meta['first_name'];
$newArray['last_name'] = $meta['last_name'];

如果键数不多,这很有用。

如果钥匙很多;然后你可以去

$requiredKeys = ['nickname','first_name','last_name'];
foreach ($arr as $key => $value) {

        if(in_array($key,$requiredKeys))
                $newArray[$key] = $meta[$key];
}