How can I optimize my array_join (simulates a LEFT JOIN) function?

后端 未结 1 2020
太阳男子
太阳男子 2021-01-23 00:06

I wrote the following code to take arrays in PHP and \"join\" them together the way that a LEFT JOIN would in MySQL. For my sake I wrote the function using foreach and passed th

相关标签:
1条回答
  • 2021-01-23 00:38

    Better?

    function array_join($original, $merge, $on) {
        if (!is_array($on)) $on = array($on);
        foreach ($merge as $remove => $right) {
            foreach ($original as $index => $left) {
                foreach ($on as $from_key => $to_key) {
                    if (!isset($original[$index][$from_key])
                    || !isset($right[$to_key])
                    || $original[$index][$from_key] != $right[$to_key])
                        continue 2;
                }
                $original[$index] = array_merge($left, $right);
                unset($merge[$remove]);
            }
        }
        return array_merge($original, $merge);
    }
    
    0 讨论(0)
提交回复
热议问题