Isius
Isius

Reputation: 6974

How do I select last array per key in a multidimensional array

Given the following php array

$a = array(
    array('a'=>'111','b'=>'two','c'=>'asdasd'),
    array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
    array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
    array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);

how can I return only the last array per array key 'a'?

Desired result:

$new = array(
    array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
    array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);

Upvotes: 0

Views: 42

Answers (1)

Levi Morrison
Levi Morrison

Reputation: 19552

If I were you, I'd try to store it in a better format that makes retrieving it a bit easier. However, if you are stuck with your format, then try:

$a = array(
    array('a'=>'111','b'=>'two','c'=>'asdasd'),
    array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
    array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
    array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);

$tmp = array();
foreach ($a as $value) {
    $tmp[$value['a']] = $value;
}

$new = array_values($tmp);

print_r($new);

Upvotes: 3

Related Questions