2

我从数据库中检索了一些数据,其结构如下:

[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,但既然不是,我选择使用PHP.net 评论中列出的多维 array_flip,或者使用我自己的逻辑:

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'];
}

我知道这很简单,但感觉就像我在这里重新发明轮子一样。是否有一种可接受的、更优化的方法可用,还是我对此感到奇怪?

4

1 回答 1

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;
}
于 2012-09-03T21:36:25.137 回答