【问题标题】:Sort Array and maintains the index排序数组并维护索引
【发布时间】:2019-08-17 13:02:10
【问题描述】:

我试图获得用户提供的值和索引数组元素之间的最小差异。 例如用户提供了 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)

【问题讨论】:

    标签: arrays indexing asort


    【解决方案1】:
    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);}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 2019-09-10
      相关资源
      最近更新 更多