PortyR
PortyR

Reputation: 385

Why are some array values being overwritten and others are not? PHP

I have a MySQL query that combines the data from the transcriber table with data from a table that lists their certifications. Some transcribers may have more than one certification.

I am finding that some transcribers come up once for each certification that they have, as they should. For other transcribers, the first array value gets overwritten by the second. It seems to me that if a transcriber has two certifications, one with certId 1 and one with certId 3, the 3 overwrites the 1. This doesn't happen with a certId of 2, 4, 5, 6, or 7 (any combination besides 1 and 3).

Here is my code:

public function getTranscribersAndTheirCertificationsList() {
    $Q = $this->read_db->query('SELECT t.*, tc.certId, tc.regNum, c.certName FROM transcriber t 
        JOIN transcribercertifications tc ON t.id = tc.tid 
        JOIN certifications c ON tc.certId = c.id');
    return $Q->result_array();
}

The code below takes the data passed in from above and processes it:

$list = $this->MTranscriber->getTranscribersAndTheirCertificationsList();
foreach ($list as $t) {
    $key = explode(' ', trim($t['name']));
    $key = preg_replace('/[()]/','', $key);
    $key = array_reverse($key);
    $key = implode(' ', $key) . $t['id'];
    $t['cet'] = $t['certName'] . ($t['regNum'] ? '-' . $t['regNum'] : '');
    if ($t['certId'] == 2 || $t['certId'] == 5) {
        $data['cetlist']['tta'][$key] = $t;
    } else {
        $data['cetlist']['cet'][$key] = $t;
    }
}
if (!empty($data['cetlist']['cet'])) {
    ksort($data['cetlist']['cet']);
}
if (!empty($data['cetlist']['tta'])) {
    ksort($data['cetlist']['tta']);
}

If I echo out $t, the data looks good. For some reason, when the $t gets added to each array in the else branch, the first value is being overwritten in the cases where certId = 1 and certId = 3. I tried using array_push and array_merge, but didn't get the results I need either.

EDIT Here is some sanitized data:

Array
(
[Doe John9] => Array
    (
        [id] => 9
        [name] => John Doe
        [email] => 
        [homephone] => 
        [cellphone] => 
        [address1] => 1 Main Street
        [address2] => 
        [city] => ABC
        [stateregion] => 
        [zipcode] => 99999
        [cet] => CET-485
        [certId] => 3
        [regNum] => 485
        [certName] => CET
    )
)

If John Doe has another certification with a certId of 1 (CER), it gets overwritten by the data above and I only get the one above. I should get one for the CER and one for the CET.

Upvotes: 1

Views: 66

Answers (1)

Rentabear
Rentabear

Reputation: 300

The key you use to save the transcriber to the array is the same independant of the certId. So you'll always override the previous entries. If you want to add multiple versions of the transcriber you should add the certId to the key.

Upvotes: 2

Related Questions