Search code examples
phparraysarray-merge

Merging arrays created by a function


I have a PHP array main_array and in my template file I have a function that accesses this array. Within that function I have another function that can get and display main_array values based on whatever key is queried on the actual front end page. I use this to get meta data stored in main_array based on the URL or ID of a page or some other query.

Example: In front end page I have

$prod_id = [
    ["query" => "prod-1"],
    ["query" => "prod-2"]
];

In main_array I have

$main_array = [
    ["name" => "prod-1", "tags" => "lilac, rose, wood"],
    ["name" => "prod-2", "tags" => "wood, plastic"]
];

In template file I have a loop and the lookup function which gets the tags of the relevant products and creates an array for each

function lookup($lookup_value, $lookup_array, $lookup_column, $result_column) {
    foreach ($lookup_array as $item) {
            if ($item[$lookup_column] == $lookup_value) {
                return $item[$result_column];
            }
    }
    return false;
}   

foreach ($prod_id as $tags) {
    $result = lookup($tags["query"],$main_array,"name","tags");
}

This works fine, it will create two arrays with the two sets of tags. The problem I am having is merging the arrays created by the lookup function so I can then get the unique values - I don't want the tag "wood" to appear twice. I have messed about with array_merge for a while but it's not outputting as expected.


Solution

  • I think you're close, just missing a couple steps

    $unique_tags = [];
    foreach ($prod_id as $tags) {
    
        $result = lookup($tags["query"],$main_array,"name","tags");
    
        // `tags` is a string, so explode it to get an array
        $result_as_array = explode( ',', $result );
    
        // merge like you mentioned
        $merged_array = array_merge( $unique_tags, $result_as_array );
    
        // make sure there's no duplicate entries
        $merged_array_no_duplicates = array_unique( $merged_array );
    
        // re-assign to the array where you want to store all tags
        $unique_tags = $merged_array_no_duplicates;
    
    
    }