Relate data where value in one array is found in a comma-separated string of another array

Viewed 71

I would like to retrieve data from two arrays.

$people = array (
    array (
        'people-name' => 'Albert',
        'people-pic' => 'link to pict'
    ),
    array (
        'people-name' => 'Josh',
        'people-pic' => 'link to pict'
    ),
    array (
        'people-name' => 'James',
        'people-pic' => 'link to pict'
    )
);

$projects = array (
    array (
        'project-name' => 'Project of JJH',
        'people-name' =>'Josh, James, Henry'    
    ),          
    array (
        'project-name' => ' Project of Albert',
        'people-name' =>'Albert'
    ),  
);

Here is my php:

    <?php foreach ($people as $key => $val)  { ?>
    
    <p>Name:<?php echo $val['people-name']; ?></p>
        
        <?php foreach ($projects as $k => $v){  

        //$final_array = array_column ($projects, 'people-name');
        //$other_array = array_column ($people, 'people-name');
        //$codes = implode (',', $final_array);
       
       if ( ($val['people-name'] == $v['people-name']) ){      
        $result = $v['project-name'];
        ?>
        <p>Project Name : <?php echo $result; ?></p>            
    <?php } ?>
<?php }
} ?>

Here is the result:

Name:Albert

Project Name : Project of Albert

Name:Josh

Name:James

For Josh and James, I need to have

Project Name : Project of JJH

How to do this?

1 Answers

To ensure that you are making whole name matches and to reduce the Big O time complexity of this task, set up a lookup array by exploding name strings and assigning projects to respective names individually.

Then iterate your $people array and reference a person's projects using the name keys in the lookup.

Code: (Demo with extended sample data)

$lookup = [];
foreach ($projects as $project) {
    foreach (explode(', ', $project['people-name']) as $name) {
        $lookup[$name][] = $project['project-name'];
    }
}
foreach ($people as $person) {
    echo "<p>Name: {$person['people-name']}</p>\n";
    printf(
        "<p>Projects: %s</p>\n\n",
        implode(', ', $lookup[$person['people-name']] ?? ['[no projects]'])
    );
}

Output from extended sample showing person on two projects and person on no projects:

<p>Name: Albert</p>
<p>Projects: Project of JJHA,  Project of Albert</p>

<p>Name: Josh</p>
<p>Projects: Project of JJHA</p>

<p>Name: James</p>
<p>Projects: Project of JJHA</p>

<p>Name: Jo</p>
<p>Projects: [no projects]</p>

By avoiding the use of strpos(), Jo is not confused with Josh while iterating.

Related