存储具有相同值

时间:2017-02-10 04:39:48

标签: arrays laravel laravel-5

来自$hasil的数组就像这样

Array ( [24] => 0.29883576167978 [20] => 0.29883576167978 [20,24] => 0.17930145700787 [34] => 0.12390406380914 [26,34] => 0.099123251047315 )

我试试这个

$newArray = array();
    $i = 0;
    foreach ($hasil as $key => $value) {
      $newArray[$i] = $key . '|' . $value;
      $i++;
    }

    for ($i = 0; $i < sizeof($newArray); $i++) {
      for ($j = 0; $j < sizeof($newArray) - 1; $j++) {
        $n1 = explode("|", $newArray[$j]);
        $n2 = explode("|", $newArray[$j+1]);

        if (doubleval($n1[1]) < doubleval($n2[1])) {
          $temp = $newArray[$j];
          $newArray[$j] = $newArray[$j + 1];
          $newArray[$j + 1] = $temp;
        }
      }
    }

    $idObjeks = array();
    $i = 0;
    foreach ($newArray as $key) {
      $ex1 = explode("|", $key);
      $ex2 = explode(",", $ex1[0]);
      foreach ($ex2 as $ky) {
        $idObjeks[$i] = $ky;
        $i++;
      }
    }

    $hasil = array();
    foreach ($newArray as $key) {
      $ex = explode("|", $key);
      $hasil[$ex[0]] = $ex[1];
    }

    // I think wrong in this code ***
    // I want save $hasil with the biggest or the biggest with same value in database 
    // when I print_r there are not the same value and the biggest value
    $sameValue = array();
    for ($i = 0; $i < sizeof($hasil) - 1; $i++) {
      if (current($hasil) == next($hasil)) {
        $sameValue[$i]['key'] = key($hasil);
        $sameValue[$i]['value'] = current($hasil);
        $sameValue[$i+1]['key'] = key($hasil);
        $sameValue[$i+1]['value'] = next($hasil);
      } else {
        prev($hasil);
        $sameValue[$i]['key'] = key($hasil);
        $sameValue[$i]['value'] = current($hasil);
        break;
      }
    }

并像这样存储在数据库中。

$hasilInsert = array();
    foreach ($sameValue as $key => $value) {
      $hasilInsert = array(
        'id_wi' => $wisatawan->id,
        'hasil' => $value['key'],
        'nilai' => $value['value']
        );
      $xy = HasilWisataTemp::insert($hasilInsert);
    }

此代码有什么问题?或者在数据库中存储相同值数组的任何简单方法?因为我想存储数组的值相同。

感谢关注。

1 个答案:

答案 0 :(得分:1)

尝试

protected $fillable = [
    'id_whi', 'hasil', 'nilai'
];

将所有这些属性放在可填充的数组中。

$arr = [
    [24] => 0.29883576167978, 
    [20] => 0.29883576167978
];

foreach($arr as $key => $value) {
    HasilWisataTemp::create([
        'id_wi' => $wisatawan->id,
        'hasil' => $value['key'], //24... 20
        'nilai' => $value['value'] // 0.29883576167978.... 0.29883576167978
    ]);
}

<强>更新 格式化和保存数组

loginWithAuth0