happypete
happypete

Reputation: 43

Selecting certain elements from an array

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] => [email protected]
        [DESCRIPTION] => CHECKIN:  04/08/2012\nCHECKOUT: 04/17/2012\nNIGHTS:   14\nPHO
        [NE] =>     +1 504 914 0591\nEMAIL:    [email protected]\nPROPERTY: Breathtaking views over the lake\n
        [SUMMARY] => Name here (ED5ASC)
        [LOCATION] => Breathtaking views over the lake
    )

[1] => Array
    (
        [DTEND] => 20131231
        [DTSTART] => 20131226
        [UID] => [email protected]
        [DESCRIPTION] => CHECKIN:  12/26/2013\nCHECKOUT: 12/31/2013\nNIGHTS:   5\nPHON
        [E] =>     +44 7843 387767\nEMAIL:    [email protected]\nPROPERTY: Breathtaking views over the lake\n
        [SUMMARY] => Name here (JrtyKW9)
        [LOCATION] => Breathtaking views over the lake
    )

[2] => Array
    (
        [DTEND] => 20121123
        [DTSTART] => 20121117
        [UID] => [email protected]
        [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.

Upvotes: 3

Views: 61

Answers (2)

CrayonViolent
CrayonViolent

Reputation: 32532

$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.

Upvotes: 3

Michael D.
Michael D.

Reputation: 1837

you can delete key/value hashes from each element

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

in this case it's faster to make a new array, like crayon violent suggested.

Upvotes: 1

Related Questions