排序数组并维护索引

时间:2019-03-27 02:58:40

标签: arrays indexing asort

我正在尝试使用户提供的值与索引数组的元素之间的值差异最小。 例如,用户提供了90。获得90与“容量”值之间的差。

// Output of the $unallocated array variable     
array (size=2)
  0 => 
    object(stdClass)[28]
      public 'id' => string '9' (length=1)
      public 'name' => string 'ICT LR B' (length=8)
      public 'capacity' => string '200' (length=3)
  1 => 
    object(stdClass)[29]
      public 'id' => string '8' (length=1)
      public 'name' => string 'ICT LR A' (length=8)
      public 'capacity' => string '120' (length=3)

// Code Snippet    
$num_stud = $this->input->post('total_student');
foreach ($unallocated as $un) 
{
    if($num_stud < $un->capacity){
        $difference[] = $un->capacity - $num_stud;
        $hl[] = $un->id; 
    }
}

asort($difference);
$arrlength = count($difference);
for($x = 0; $x < $arrlength; $x++) {
   $rec[] = array(
       'difference' => $difference[$x],
       'hall_id' => $hl[$x]
   );
}

将$ difference数组变量按升序排列,但我希望仍然能够确定哪个元素具有该特殊区别。

 // instead of having this  
 array (size=2)
  0 => 
      array (size=2)
      'difference' => int 100
      'hall_id' => string '9' (length=1)
  1 => 
      array (size=2)
      'difference' => int 20
      'hall_id' => string '8' (length=1)

// I want to have this. I want it to be sorted in the ascending order of the difference as 20 is less than 100 in the difference 
 array (size=2)
  0 => 
      array (size=2)
      'difference' => int 20
      'hall_id' => string '8' (length=1)
  1 => 
      array (size=2)
      'difference' => int 100
      'hall_id' => string '9' (length=1)

1 个答案:

答案 0 :(得分:0)

public function cluster($doc=NULL){
$number_of_clusters = $_POST['num_clust'];
$initial_k_clusters = $this->algorithm_model->initial_k_clusters($number_of_clusters);

//     $ clusters = $ this-> algorithm_model-> all_clusters();

$groups = array();
$i = 0;
foreach ($clusters as $cluster) {
$distances = array();
foreach ($initial_k_clusters as $centroid){ 
++$i;
$distance[$i] = abs($cluster['cluster'] - 
$centroid['cluster']);
array_push($distances, $distance[$i]);
}

$x = 0;
do{
$min = min($distances);
switch ($min) {
case $distances[$x]:
$groups[$x][]=$cluster['doc_id'];
break;
}
$x++;  
}while ($x < $number_of_clusters);
$x = 0;
unset($distances);}