phpunk Posted July 5, 2012 Share Posted July 5, 2012 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)); ?> Quote Link to comment https://forums.phpfreaks.com/topic/265278-inner-join-php-arrays/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.