1

我有一个 csv 文件中的数据,我使用以下方法将其组织成一个多维数组:

$handle = fopen("bankdata.csv", "r");

while(($data = fgetcsv($handle, 0 ,",")) !==FALSE) {

    $transactions[] = $data;

 }  

数组现在看起来像这样:

Array
(
[0] => Array
    (
        [0] => 2000
        [1] => paycheck
        [2] => credit
    )

[1] => Array
    (
        [0] => 75
        [1] => grocery
        [2] => debit
    )

[2] => Array
    (
        [0] => 45
        [1] => gas
        [2] => debit
    )

[3] => Array
    (
        [0] => 900
        [1] => investments
        [2] => credit
    )

[4] => Array
    (
        [0] => 1500
        [1] => bonus
        [2] => credit
    )  

现在我想命名每个嵌套数组中的键。我想我会创建一个具有等量嵌套数组的新多维数组,它们的值是我想添加到原始数组中的键的预期名称,然后执行“array_combine”:

$names = array('amount','source','type');

$run = 1;

while($run < 6){
  $run = $run +1;  
  $names2[] = $names;   
}

$combine = array_combine($names2, $transactions);
4

2 回答 2

1

您可以使用数组组合:

$keynames=array('amount','source','type');
foreach ($transactions as $i=>$row) {
   $transactions[$i]=>array_combine($keynames, $row);
}

解决问题的正确方法是不要将数据读入数组然后对其进行转换——在读取数据时进行转换

while(($data = fgetcsv($handle, 0 ,",")) !==FALSE) {
    $transactions[]=array_combine($keynames, $data);
}

BTW PHP 不做多维数组——它们是嵌套的。尽管手册中说了什么,但它们只模拟多维数组。

于 2013-08-19T21:08:15.990 回答
1

尝试以下操作:

$arr = array(
    array(2000, 'paycheck', 'credit'),
    array(75, 'grocery', 'debit'),
    array(45, 'gas', 'debit'),
    array(900, 'investments', 'credit'),
    array(1500, 'bonus', 'credit')
);

$keys = array('amount','source','type');

// $a will make a reference to the array within $arr
// and override the array
foreach($arr as &$a)
{
    // Override the array keys
    $a = array_combine($keys, $a);
}

/* Output:
Array
(
    [0] => Array
        (
            [amount] => 2000
            [source] => paycheck
            [type] => credit
        )

    [1] => Array
        (
            [amount] => 75
            [source] => grocery
            [type] => debit
        )

    [2] => Array
        (
            [amount] => 45
            [source] => gas
            [type] => debit
        )

    [3] => Array
        (
            [amount] => 900
            [source] => investments
            [type] => credit
        )

    [4] => Array
        (
            [amount] => 1500
            [source] => bonus
            [type] => credit
        )

)
*/
于 2013-08-19T21:09:29.287 回答