Creating a hash map in PHP using array -
i'm trying create hash map or 2d array using arrays in php. values hardcoded in, have. tried code in comments, realized wasn't making 2d array.
$hash_map = array(); $query = $this->students_m->getstudentclasses('2'); foreach ($query->result_array() $key1=>$value1) { $query2 = $this->students_m->getstudentsinfo('2', '10', '3'); foreach ($query2->result_array() $key2=>$value2) { /* if (!in_array($value2['name'],$hash_map, true)) { array_push($hash_map, $value2['name']); } */ hash_map[$value1['id']][] = $value2['name']; } }
id , student_name names of columns sql table. ran code , couple variations of it:
foreach ($hash_map $student) { echo $student; echo "<br>"; }
and wasn't able correct output. i'd each value maps array of unique values, example of i'm going looks like:
hash_map['10'][0] = '123'
hash_map['10'][1] = '124'
hash_map['10'][2] = '125'
hash_map['3'][1] = '123'
hash_map['3'][2] = '128'
is have close? point me in right direction?
when working multi dimension arrays want check existing keys, not existing values.
your commented out code should this
if (!array_key_exists($value1['id'],$hash_map)) { $hash_map[$value1['id']] = array(); }
that setup outer array, allowing add elements it.
there couple of ways prevent duplicate data being put second part of array. if assume name field unique, or want know unique entries, then
if (!in_array($value2['name'],$hash_map[$value1['id']]) { $hash_map[$value1['id'][]=$value2['name']; }
will work fine, however, user's names might not unique (john smith anyone?), , might want check $value2['id'] in manner instead.
one way accomplish use $value2['id'] key second part of array
$hash_map[$value1['id'][$value2['id']]=$value2['name'];
this prevent duplicate keys existing since overwrite 1 another.
if inner array must start @ 0 , continue x x number of entries, "exists" array best
$exists = array(); if (!in_array($value2['id'],$exists)) { $hash_map[$value1['id']][]=$value2['name']; $exists[]=$value2['id']; }
then, printing want like:
foreach ($hash_map $student) { echo implode(",",$student); echo "<br>"; }
Comments
Post a Comment