3

我正在尝试从数组中删除除 DTSTART 和 DTEND 之外的所有内容

所以我试图转换这个:

Array
(
[0] => Array
    (
        [DTEND] => 20130417
        [DTSTART] => 20130403
        [UID] => cerog90g7-fcqls51z0wteew@airbnb.com
        [DESCRIPTION] => CHECKIN:  04/08/2012\nCHECKOUT: 04/17/2012\nNIGHTS:   14\nPHO
        [NE] =>     +1 504 914 0591\nEMAIL:    testhere@email.com\nPROPERTY: Breathtaking views over the lake\n
        [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\nCHECKOUT: 12/31/2013\nNIGHTS:   5\nPHON
        [E] =>     +44 7843 387767\nEMAIL:    floraking@hotmail.com\nPROPERTY: Breathtaking views over the lake\n
        [SUMMARY] => Name here (JrtyKW9)
        [LOCATION] => Breathtaking views over the lake
    )

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

)

看起来像这样:

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

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

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

我已经搜索了很多选项,但我需要能够只选择这两个元素并丢弃其余元素,我将使用具有不同值的不同数组,因此不能只指定要删除的元素各不相同。

4

2 回答 2

3
$newArray = array();
foreach ($array as $k => $v) {
  $newArray[$k]['DTEND'] = $v['DTEND'];
  $newArray[$k]['DTSTART'] = $v['DTSTART'];
}

编辑:另一种选择,因为您提到尝试使用数组迭代器函数之一来完成它..

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

编辑2:因为我没有生命……还有另一种选择……

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

我不知道哪个最快/最有效,但我的钱可能排在第二位。

于 2013-11-15T01:26:19.993 回答
1

您可以从每个元素中删除键/值哈希

unset($array[0]['UID']);
unset($array[0]['DESCRIPTION');
//...
unset($array[999]['UID']);
unset($array[999]['DESCRIPTION');

在这种情况下,制作一个新数组会更快,就像蜡笔暴力建议的那样。

于 2013-11-15T01:38:12.140 回答