Skip to content
Advertisement

Using php class for storing and grouping data to each person in array using different IDs

I have SQL exercise where I should convert table data into a print sentence where every person has phone numbers. For example

Alice: n1  (person ID here is 1)
Alice: n2 (person ID here is 1)
Alice: n5 (person ID here is 4)
Bob: n3 (person ID here is 2)
Carol: n4 (person ID here is 3)

But instead Alice: n1 and Alice: n2 it should be Alice: n1, n2. Alice: n5 has a different ID and we aren’t limited to a unique name. So we should get :

Alice: n1, n2 
Alice: n5 
Bob: n3 
Carol: n4 

I’m pretty sure I missed something since I’m getting each person phone(s) separately in $personList

require_once 'Person.php';

function statementToPersonList($stmt) {

    $dictionary = [];
    $personList = [];

    foreach ($stmt as $row) {

        $id = $row['id'];
        $name = $row['name'];
        $number = $row['number'];

        $person = new Person($id, $name);
        $key = array_search($id, array_column($personList, 'id'));
        if (!$key) {
            $person ->addPhone($number);
            $personList[] = $person;
        }else{
            $personList[$key] ->addPhone($number);
        }
    }
    return $personList;

addPhone() is just a function in Person class file

public function addPhone($phone) {
        $this->phones[] = $phone;
    }

Maybe I should use up this $dictionary = [] array, to store values, but I’m still confused how should I do it then. Cannot use database to handle the concatenation.

Advertisement

Answer

A more efficient way to do this would be to index your array by ID. Your code becomes:

/**
 * @return Person[]
 */
function statementToPersonList(iterable $stmt): array
{
    $personList = [];

    foreach ($stmt as $row) {
        $id = $row['id'];
        $name = $row['name'];
        $number = $row['number'];

        if (!isset($personList[$id])) {
            $personList[$id] = new Person($id, $name);
        }

        $personList[$id]->addPhone($number);
    }

    return $personList;
}

Note: you can also return array_values($personList) if you don’t want the array indexed by ID when retrieving it.

Demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement