开发者

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开发者_如何学Go 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


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']);
}


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.


$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'];


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜