Peter
Peter

Reputation: 1296

php multidimensional array get first date value

I need help once again. I have an array and I need to extract earliest day weight value.

EDIT - EDIT - EDIT


array (
  3 => 
  array (
    'id' => '20110211',
    'Date' => '2011-02-11',
    'Weight' => '195',
  ),
  4 => 
  array (
    'id' => '20110213',
    'Date' => '2011-02-13',
    'Weight' => '160',
  ),
  6 => 
  array (
    'id' => '20110310',
    'Date' => '2011-03-10',
    'Weight' => '200',
  ),
  12 => 
  array (
    'id' => '20110301',
    'Date' => '2011-03-01',
    'Weight' => '55',
  ),
  21 => 
  array (
    'id' => '20110215',
    'Date' => '2011-02-15',
    'Weight' => '120',
  ),
  25 => 
  array (
    'id' => '20110322',
    'Date' => '2011-03-22',
    'Weight' => '250',
  ),
)

I've edited this and this code works:


function sortByDate ($arr1, $arr2)
{
   return strcmp($arr1['Date'], $arr2['Date']);
}
// $arr is your array
usort($weight_tracker, 'sortByDate');
$earliest = $weight_tracker[0]['Weight'];
echo $earliest;

But since I have a form on this page which updates the array when array is updated - I got message Fatal error: Cannot use string offset as an array in

EDIT -> I've re-declared this as string, hence the ERROR ! be careful when using global and includes as everything can become a mess ! PHP is forgiving, but that "forgiveness" can cost a lot of time later on... :)

Thanks,
Peter

Upvotes: 1

Views: 1977

Answers (4)

Phoenix
Phoenix

Reputation: 4536

I noticed that the dates are in reverse order with the latest date being pulled in first, and the earliest date last. Will it always be like that? If so, you can do this:

$index = count($array) - 1;
$earliestdate = $array[$index]['Date'];

You could also use array_reverse() to invert the array and make the first element the formerly last element.

If this is being pulled in from MySQL you could also alter the query to ORDER BY 'Date' DESC (or is it ASC that would get you what you want, can't remember)

Upvotes: 0

Wiseguy
Wiseguy

Reputation: 20883

You could sort the array with a custom callback using usort() and then take the first element.

// $arr is your array
usort($arr, 'sortByDate');
$earliest = $arr[0];

function sortByDate ($arr1, $arr2)
{
   return strcmp($arr1['Date'], $arr2['Date']);
}

Upvotes: 2

Emil Vikström
Emil Vikström

Reputation: 91963

This is one way of doing it:

function filter_min($a, $b) {
  return ($a['Date'] < $b['date']) ? $a : $b;
}

$result = array_reduce($array, 'filter_min');
echo $result['Weight'];

Another way is to simply iterate over the array and find the smallest date.

Upvotes: 1

Marc B
Marc B

Reputation: 360742

$smallest = null; // array index of entry with smallest weight.
foreach ($array as $idx => $data) {
    if (($data['Weight'] < $array[$smallest]['Weight']) || (is_null($smallest))) {
      $smallest = $idx; // found a small weight, so save the index
    }
}

echo $array[$smallest]['Date'];

Upvotes: 0

Related Questions