2017-02-10 215 views
0

$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); 
    } 

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

感谢您的关注。

+0

什么是你的问题? – Chris

+0

如何使数组保存相同的值? –

+0

你可以展示你已经尝试过什么,失败了吗?你有什么*好像*好 – Chris

回答

1

尝试

$xy = HasilWisataTemp::create([ 
    'id_wi' => $wisatawan->id, 
    'hasil' => $value['key'], 
    'nilai' => $value['value'] 
]); 

把所有这些属性的可填充阵列。

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

错误'Model.php中的MassAssignmentException行452: id_wi' –

+0

检查更新的答案 – EddyTheDove

+0

我认为这是任何错误的逻辑,当我找到具有相同值的数组。不是当我存储数组。 –

相关问题