duanou1904 2013-11-15 01:22
浏览 145
已采纳

从数组中选择某些元素

I'm trying to remove everything from an array except DTSTART & DTEND

So I'm trying to convert this:

Array
(
[0] => Array
    (
        [DTEND] => 20130417
        [DTSTART] => 20130403
        [UID] => cerog90g7-fcqls51z0wteew@airbnb.com
        [DESCRIPTION] => CHECKIN:  04/08/2012
CHECKOUT: 04/17/2012
NIGHTS:   14
PHO
        [NE] =>     +1 504 914 0591
EMAIL:    testhere@email.com
PROPERTY: Breathtaking views over the lake

        [SUMMARY] => Name here (ED5ASC)
        [LOCATION] => Breathtaking views over the lake
    )

[1] => Array
    (
        [DTEND] => 20131231
        [DTSTART] => 20131226
        [UID] => rtyrtyg90g7--t520wkwqv2i8@airbnb.com
        [DESCRIPTION] => CHECKIN:  12/26/2013
CHECKOUT: 12/31/2013
NIGHTS:   5
PHON
        [E] =>     +44 7843 387767
EMAIL:    floraking@hotmail.com
PROPERTY: Breathtaking views over the lake

        [SUMMARY] => Name here (JrtyKW9)
        [LOCATION] => Breathtaking views over the lake
    )

[2] => Array
    (
        [DTEND] => 20121123
        [DTSTART] => 20121117
        [UID] => ntry5rxts23--qe9rtyrywi0@airbnb.com
        [SUMMARY] => Not available
    )

)

to look like this:

Array
(
[0] => Array
    (
        [DTEND] => 20130417
        [DTSTART] => 20130403
    )

[1] => Array
    (
        [DTEND] => 20131231
        [DTSTART] => 20131226
    )
)

[2] => Array
    (
        [DTEND] => 20121123
        [DTSTART] => 20121117
    )
)

I've searched for loads of options but I need to be able to just select these two elements and discard the rest, I will be using it with different arrays that have different values so can't just specify the elements to remove as they will vary.

  • 写回答

2条回答 默认 最新

  • doumei4964 2013-11-15 01:26
    关注
    $newArray = array();
    foreach ($array as $k => $v) {
      $newArray[$k]['DTEND'] = $v['DTEND'];
      $newArray[$k]['DTSTART'] = $v['DTSTART'];
    }
    

    edit: an alternative, since you mentioned trying to do it with one of the array iterator functions..

    array_walk($array, function(&$v){
      $v = array('DTEND' => $v['DTEND'],'DTSTART' => $v['DTSTART']); 
    });
    

    edit2: because I have no life...yet another alternative...

    array_walk($array, function(&$v){
      $v = array_intersect_key($v, array_flip(preg_grep('~^DT(END|START)$~', array_keys($v))));
    });
    

    I don't know which one is fastest/most efficient but my money is probably on the 2nd one.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line