【问题标题】:PHP: How to copy elements from an associative array and place them at the beginning of the array?PHP:如何从关联数组中复制元素并将它们放在数组的开头?
【发布时间】:2010-03-12 20:51:35
【问题描述】:

我将在选择菜单中使用一系列国家/地区:

array(
    [0] => " -- Select -- "
    [1] => "Afghanistan"
    [3] => "Albania"
    [4] => "Algeria"
    [39] => "Canada"
    [47] => "USA"
)
//etc...

我想复制加拿大和美国条目的创建副本并将它们放在我的数组的前面。所以数组最终应该是这样的:

array(
    [0] => " -- Select -- "
    [47] => "USA"
    [39] => "Canada"
    [1] => "Afghanistan"
    [3] => "Albania"
    [4] => "Algeria"
    [39] => "Canada"
    [47] => "USA"
)
//etc...

数组键对应于它们在数据库中的ID,所以我不能更改键。我怎样才能做到这一点?

解决方案

我意识到这是不可能的。当您尝试使用重复键在数组中设置值时,它会覆盖第一个键。我想出了一个不同的解决方案,但接受了评分最高的答案。

【问题讨论】:

  • 一个关联数组每个键只能包含一次。
  • 您可能不应该为了显示而篡改数组。相反,在您的模板中完成工作。
  • KennyTM,你是对的......我没有意识到,但我想要实现的目标是不可能的。

标签: php arrays


【解决方案1】:

代替使用一维数组作为id=>值,可以使用二维数组,比如

$countries = array(
    0 => array(
                   'country_id' => 47,
                   'country' => 'USA'
               ),
    1 => array(
                   'country_id' => 39,
                   'country' => 'Canada'
               ),
    2 => array(
                   'country_id' => 1,
                   'country' => 'Afghanistan'
               ),
    ......
);

【讨论】:

    【解决方案2】:

    您可以在 html 中手动添加它们。您可以复制并粘贴循环,将其发送到 2 元素数组。您可以将循环变成一个函数,然后使用 2 元素数组和更长的数组调用它。您可以将数组生成为 [0..inf] => Array($key, $value) 然后使用 list($key, $val) = $arr[x] 获取键值,从而使您能够手动添加美国和加拿大没有问题。

    【讨论】:

      【解决方案3】:

      由于您明确想要重复,您可以只使用数组而不是关联数组。

      array(
          [0] => " -- Select -- "
          [1] => array(name: "Afghanistan", code: 1)
          [2] => "array(name: Albania", code: 3)
      )
      

      等等,或者可以创建一个Country 对象并拥有一个数组。

      class Country {
          public $name;
          public $code;
          ..
      }
      
      $countries[] = new Country('USA', 47);
      $countries[] = new Country('Canada', 39);
      $countries[] = new Country('Afghanistan', 1);
      ...
      

      【讨论】:

        【解决方案4】:

        出于可用性的目的,在选择菜单中列出两次国家/地区确实不是一件好事。这有点令人困惑。

        但是,如果您有心,为什么不使用这个循环遍历关联数组:

        $top_countries = array(
            [0] = "USA";
            [1] = "Canada";
        )
        

        然后

        foreach($top_countries as $top_of_list) {
            foreach($list_of_countries as $this_country) {
                if($this_country == $top_of_list) {
                    $stored_string .= // Select HTML formatting with $this_country;
                }
            }
        }
        
        // Pointer reset and rest of the code 
        // to add rest of the countries.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-02
          • 1970-01-01
          相关资源
          最近更新 更多