3

Hi I have an array that looks like this :

Array ( [0] => Array ( [x] => 01 [y] => 244 ) [1] => Array ( [x] => 02 [y] => 244 ) [2] => Array ( [x] => 03 [y] => 244 ) [3] => Array ( [x] => 04 [y] => 243 ) [4] => Array ( [x] => 05 [y] => 243 ) [5] => Array ( [x] => 05 [y] => 244 ) [6] => Array ( [x] => 06 [y] => 242 ) [7] => Array ( [x] => 06 [y] => 243 ) [8] => Array ( [x] => 07 [y] => 243 ) [9] => Array ( [x] => 08 [y] => 243 ) [10] => Array ( [x] => 09 [y] => 242 ) [11] => Array ( [x] => 10 [y] => 244 ) [12] => Array ( [x] => 12 [y] => 243 ) [13] => Array ( [x] => 13 [y] => 243 ) [14] => Array ( [x] => 13 [y] => 243 ) [15] => Array ( [x] => 15 [y] => 243 ) ) 

x represent days and y values of a certain variable. I would like to display an array of unique days x ( last element ) and values y pragmatically.

for example day 6 I have two y values but I want to display only the last one ( 243 ).

Thanks for help

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Kaiser
  • 43
  • 1
  • 3
  • There are already some questions on SO that are essentially the same, e.g. http://stackoverflow.com/questions/2442230/php-getting-unique-values-of-a-multidimensional-array-closed (which itself has been closed as a duplicate already) – VolkerK Mar 25 '10 at 21:31

1 Answers1

1

One way of doing this would just be to use a simple loop to generate a new array, overwriting any existing values for a given date as you go along.

Code snippet

// $data = ... your array from the question
$result = array();
foreach ($data as $value) {
    $result[$value['x']] = $value['y'];
}

print_r($result);

Outputs

Array
(
    [01] => 244
    [02] => 244
    [03] => 244
    [04] => 243
    [05] => 244
    [06] => 243
    [07] => 243
    [08] => 243
    [09] => 242
    [10] => 244
    [12] => 243
    [13] => 243
    [15] => 243
)

There are numerous alternative approaches (or variations on the theme) if the above is not suitable for you.

salathe
  • 51,324
  • 12
  • 104
  • 132