Mading Ne
Mading Ne

Reputation: 133

store array with same value

my array from $hasil is like this

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

I'm try like this

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

and store in database like this.

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

What's wrong in this code? Or any simple way to store same value array in database? Because I want store the array just the same value.

Thank for attention.

Upvotes: 0

Views: 251

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Try

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

Put all those attributes in a fillable array.

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

Update Formatting and saving the array

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

Upvotes: 1

Related Questions