为重复键值创建多维数组

时间:2013-03-18 23:56:25

标签: php arrays

我试图从csv中读取数组值并创建属于主键字段的子数组。例如,我说我有以下阵列结构&内容...

$events['venue-id'] = 55
$events['event-date'] = 19/02/13;
$events['event-name'] = 'Sports Day';

$events['venue-id'] = 76
$events['event-date'] = 22/02/13;
$events['event-name'] = 'Gala Event';

$events['venue-id'] = 55
$events['event-date'] = 29/03/13;
$events['event-name'] = 'Some Other Event';

使用venue-id作为父数组中的键的最佳方法是什么?将与其相关的其他数据分配给子数组?基本上是一对多的关系。

2 个答案:

答案 0 :(得分:0)

如果你愿意,你可以像这样构建它:

$events = array( 
  "55" => array(
    "event-date" => "19/02/03",
    "event-name" => "Sports Day"
   ),
  "76" => array(
   ...

);

这假设没有重复的场地ID。

答案 1 :(得分:0)

试试这个:

$res              = array();
if (($handle      = fopen("your_file.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $res[$data[0]]['venue-id']         = $data[0];
        $res[$data[0]]['event-date']       = $data[1];
        $res[$data[0]]['event-name']       = $data[2];
    }
}

echo "<pre>";
print_r($res);