fork download
  1. <?php
  2.  
  3. $haystack = array(
  4. 0 => array("v1" => "aa", "v2" => ""),
  5. 1 => array("v1" => "bb", "v2" => ""),
  6. 2 => array("v1" => "cccc", "v2" => ""),
  7. 3 => array("v1" => "bb", "v2" => ""),
  8. 4 => array("v1" => "aa", "v2" => ""),
  9. 5 => array("v1" => "bb", "v2" => ""),
  10. 6 => array("v1" => "cccc", "v2" => ""),
  11. 7 => array("v1" => "bb", "v2" => ""),
  12. );
  13.  
  14. $needles = array(
  15. 0 => array("aa" => "nnnn", "bb" => "nnn", "cccc" => "n"),
  16. 1 => array("aa" => "ddd", "bb" => "dd"),
  17. );
  18.  
  19. function processNeedle(&$haystack, $needle) {
  20. $needleKeys = array_keys($needle);
  21. $needleValues = array_values($needle);
  22. $needleLen = count($needle);
  23. $haystackLen = count($haystack);
  24.  
  25. $matches = array();
  26. for ($i = 0; $i < ($haystackLen - $needleLen + 1); $i++) {
  27. $match = true;
  28. for ($j = 0; $j < $needleLen; $j++) {
  29. if ($haystack[$i + $j]["v1"] != $needleKeys[$j]) {
  30. $match = false;
  31. break;
  32. }
  33. }
  34. if ($match) {
  35. $matches[] = $i;
  36. $i += $needleLen - 1;
  37. }
  38. }
  39.  
  40. forEach ($matches as $startIdx) {
  41. for ($j = 0; $j < $needleLen; $j++) {
  42. $haystack[$startIdx + $j]["v2"] = $needleValues[$j];
  43. }
  44. }
  45. }
  46.  
  47. forEach ($needles as $needle) {
  48. processNeedle($haystack, $needle);
  49. }
  50. print_r($haystack);
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Array
(
    [0] => Array
        (
            [v1] => aa
            [v2] => ddd
        )

    [1] => Array
        (
            [v1] => bb
            [v2] => dd
        )

    [2] => Array
        (
            [v1] => cccc
            [v2] => n
        )

    [3] => Array
        (
            [v1] => bb
            [v2] => 
        )

    [4] => Array
        (
            [v1] => aa
            [v2] => ddd
        )

    [5] => Array
        (
            [v1] => bb
            [v2] => dd
        )

    [6] => Array
        (
            [v1] => cccc
            [v2] => n
        )

    [7] => Array
        (
            [v1] => bb
            [v2] => 
        )

)