我从数据库中检索了一些数据,其结构如下:
[0]
[item_id] = 197
[dice_chat_css] = "foo"
[dice_image] = "bar.png"
[1]
[item_id] = 128
[dice_chat_css] = "foo"
[dice_image] = "bar.png"
将这些数据传递给我的(PHP)应用程序的其余部分,最方便且计算成本最低的方法是使用item_id
作为索引,因为它可以节省必须遍历数组以查找值。如果这是一个扁平数组,我可以用array_flip
来完成这个,但是因为它不是,所以我选择使用多维array_flip listed in the comments on PHP.net,或者滚动我自己的逻辑:
for ($i = 0; $i < sizeOf($r); $i++){
$s[$r[$i]['item_id']]['dice_image'] = $r[$i]['dice_image'];
$s[$r[$i]['item_id']]['dice_chat_css'] = $r[$i]['dice_chat_css'];
}
我知道这很简单,但感觉就像我在这里重新发明轮子一样。是否有可接受的,更优化的方法,或者我对此感到奇怪?
答案 0 :(得分:4)
为什么不做呢
$indexed = array();
foreach ($r as $row) {
$indexed[$row['item_id']] = $row;
}
// or if you're concerned about memory (e.g. result set is large), less smooth version:
foreach ($r as $index => $row) {
$r[$row['item_id']] = $row;
unset($r[$index]); // it works ok, foreach doesn't traverse over added elements, but it isn't a good way
}
// or smoother alternative for unset(), have second array contain links to first:
$indexed = array();
foreach ($r as &$row) {
$indexed[$row['item_id']] = &$row;
}