Home>

In the part that has been processed to replace all the results obtained from the DB with the shuffle function at random
When a specific condition is newly met, it is necessary to incorporate processing that is not subject to replacement processing only within that range.
(New condition->If a number other than 0 is stored in fuga.)

hoge fuga
581468 0
481358 0
587984 0
000010 123456
000011 123456
000012 123456
891357 0
345784 0

I tried out a method that shuffles and merges fuga with numbers other than 0
If this is the case, everything that meets the condition will be fixed at the beginning or end.
Is there a better way? I would appreciate your teaching.

php
  • Answer # 1

    Do you only extract fuga that is not 0 and choose the same place to shuffle?

    $a = [
      ["hoge" =>1, "fuga" =>0],
      ["hoge" =>2, "fuga" =>0],
      ["hoge" =>3, "fuga" =>1],
      ["hoge" =>4, "fuga" =>0],
      ["hoge" =>5, "fuga" =>2],
      ["hoge" =>6, "fuga" =>3],
      ["hoge" =>7, "fuga" =>0],
      ["hoge" =>8, "fuga" =>0],
      ];
    $b = array_filter ($a, function ($x) {
      return $x ["fuga"] === 0;
      // return $x ["fuga"]! == 0;
    });
    / * Use operator === to shuffle only 0 part * /
    $c = $d = array_keys ($b);
    shuffle ($d);
    foreach ($d as $key =>$val) {
      $a [$c [$key]] = $b [$val];
    }
    print_r ($a);

  • Answer # 2

      

    This will fix everything that meets the condition at the beginning or end.

    Can I keep the original position and merge?

    Code sample

    Get yambejp's code halfway.

    $a = [
      ["hoge" =>1, "fuga" =>0],
      ["hoge" =>2, "fuga" =>0],
      ["hoge" =>3, "fuga" =>1],
      ["hoge" =>4, "fuga" =>0],
      ["hoge" =>5, "fuga" =>2],
      ["hoge" =>6, "fuga" =>3],
      ["hoge" =>7, "fuga" =>0],
      ["hoge" =>8, "fuga" =>0],
      ];
    $b = array_filter ($a, function ($x) {
      return $x ["fuga"] === 0;
    });
    shuffle ($b);
    $bi = 0;
    foreach ($a as $ai =>$val) {
        if ($val ["fuga"] === 0) {
            $a [$ai] = $b [$bi];
            $bi ++;
        }
    }