Jump to content

Inner Join PHP Arrays


phpunk

Recommended Posts

Hey all,

I'm working on a function that will Inner Join PHP arrays. I think I've got working version of it, but I was wondering how I can restructure and improve my code here.  My code is below.

 

There probably is a more elegant solution I'm missing because I'm new to programming and PHP. I plan on using this function to help me setup some data dashboards.

 

Any help is appreciated here!

 

 

 

<?php 
$test = array(
    array("a", "b", "c"),
    array(1, 2, "test"),
    array(4, 5, 6)
);

$test1 = array(
    array("c", "d", "e"),
    array(1, 2, 3),
    array("test", 5, 6)
);

function match_arrays($array1, $array2, $col1, $col2) {
    $matchcount = 0;
    for ($i = 0; $i < count($array1); $i++) {
        $match = $array1[$i][$col1];
        for ($j = 0; $j < count($array2); $j++) {
            if ($match == $array2[$j][$col2]) {
                $matches[$matchcount] = array($i, $j);
                $matchcount++;
            }
        }
    }

    return $matches;
}


function join_arrays($array1, $array2, $col1, $col2) {
    // Find matching rows 
    $matches = match_arrays($array1, $array2, $col1, $col2);

    /* For each matching row, create a new row with matching rows from both arrays 
     * and store it in a new array
     */
    for ($i = 0; $i < count($matches); $i++) {
        $joinedarray[$i] = array_merge($array1[$matches[$i][0]], $array2[$matches[$i][1]]);
        /* Maybe later get rid of duplicates, though I kind of like them 
         * because it shows the matching values. 
         */  
    }
    return $joinedarray;
}

print_r(join_arrays($test, $test1, 2, 0));
print_r(match($test, $test1, 2, 0));

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.