【问题标题】:How to display array key only if it wasn't already displayed仅在尚未显示的情况下如何显示数组键
【发布时间】:2013-06-26 23:54:04
【问题描述】:

我正在尝试制作日记类型的应用程序。因为我希望它按日期排序,所以我将要提取的日期作为键,然后将文本作为数组中的值。我想要做的只是显示一次日期,即使有两个匹配的键。

所以在下面的例子中它会理想地返回:

1/2/2013
   entry 1
   entry 2

1/5/2013
   this is another day

从此输入:

   $array = array('1/2/2013'=>'entry 1', '1/2/2013'=>'entry 2', 
'1/5/2013'=>'this is another day');

    //loop through array and echo the date and value, but only echo date if havent already 

【问题讨论】:

    标签: php arrays foreach key


    【解决方案1】:

    这种数组结构在 PHP 中是不可能的,因为数组键是唯一的。分配变量后,您会注意到数组只有两个元素,而不是三个,因为第二个条目覆盖了第一个。

    如果您可以先按日期排序条目,请考虑以下内容:

    <?php
    
    $posts = array(
        array('date' => '1/2/2013', 'title' =>'entry 1'),
        array('date' => '1/2/2013', 'title' =>'entry 2'),
        array('date' => '1/5/2013', 'title' =>'entry 3'),
    );
    
    $date = '';
    foreach ($posts as $p) {
        if ($date != $p['date']) {
            echo 'Date: ' . $p['date'] . "<br/>";
            $date = $p['date'];
        }
        echo 'Title: ' . $p['title'] . "<br/>";
    }
    

    【讨论】:

      【解决方案2】:

      您可以通过创建多维数组来允许在同一天发生多个事件。如:

      $events = array(
        '01/01/2010' => array(
          'event1', 'event2'
        ),
        '02/02/2011' => array(
          'event3', 'event5'
        )
      );
      

      在此之后,您应该能够为每个事件循环遍历数组:

      foreach($events as $date => $data) {
        echo $date .' - '. implode(',', $data);
      }
      

      【讨论】:

      • @zod - 也许是对操作的一个问题,虽然引用:I put the date that Im pulling, as the key and then the text as the value in an array 听起来可以
      【解决方案3】:

      使用

      array_key_exists

      http://php.net/manual/en/function.array-key-exists.php

      或者使用两个循环并使用array_unique

      http://php.net/manual/en/function.array-unique.php

      【讨论】:

        【解决方案4】:

        据我所知,键必须是唯一标识符,但是您可以取消设置并创建一个以该键为键的新数组,这样您就可以在其中包含多个数据,即

        Array
        0
        Date1 => string
        1
        Date2 => array("string 1","string2")
        

        【讨论】:

          猜你喜欢
          • 2015-06-26
          • 2019-10-07
          • 1970-01-01
          • 2020-03-23
          • 2023-03-19
          • 2016-12-14
          • 2016-03-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多