Imagine I have an array of data. Each item in it is another array containing ‘id’, ‘link’ and ‘display’:
$travel = array(
array(
'id' => 1,
'link' => 'bus',
'display' => 'bus'
),
array(
'id' => 2,
'link' => 'bike',
'display' => 'bicycle'
),
array(
'id' => 3,
'link' => 'cart',
'display' => 'horse and cart'
)
);
To display ‘display’ by a known id ($id) I would need to do something like:
foreach($travel as $t) {
if($t['id'] == $id) {
echo $t['display'];
break; // uuurgh, nasty...
}
}
Equally, to display ‘display’ by a known link ($link) I would need to do the same:
foreach($travel as $t) {
if($t['link'] == $link) {
echo $t['display'];
break;
}
}
To be more efficient I could create two similar arrays:
$travelID = array(
1 => array(
'link' => 'bus',
'display' => 'bus'
),
2 => array(
'link' => 'bike',
'display' => 'bicycle'
),
3 => array(
'link' => 'cart',
'display' => 'horse and cart'
)
);
$travelLink = array(
'bus' => array(
'id' => 1,
'display' => 'bus'
),
'bike' => array(
'id' => 2,
'display' => 'bicycle'
),
'cart' => array(
'id' => 3,
'display' => 'horse and cart'
)
);
and then perform the following:
echo $travelID[$id]['display'];
echo $travelLink[$link]['display'];
But is there a way of keeping all the data together whilst still being able to reference it simply/quickly?
1 Answer