douxianglu4370 2019-07-22 14:47
浏览 82
已采纳

PHP在数组的关联数组中转换数组数组

I read a csv file and got this array $rows

Array
(
 [0] => Array
     (
        [0] => Name
        [1] => Company
        [2] => Email
        [3] => City
    )
[1] => Array
    (
        [0] => Foo
        [1] => Foo & co
        [2] => foo@mail.com
        [3] => NY
    )
[2] => Array
    (
        [0] => Bar
        [1] => Bar & co
        [2] => bar@mail.com
        [3] => Las Vegas
    )
)

I would try to transform it into an associative array by filtering only some fields contained in the first array. The result should be this

Array
(
[0] => Array
   (
    ['Name'] => Foo
    ['Company'] => Foo & co
    ['Email] => foo@mail.com
   )
 [1] => Array
 (
    ['Name'] => Bar
    ['Company'] => Bar & co
    ['Email] => bar@mail.com
 )
)

Unfortunately I tried it in various ways but without success.

$name = array_search('Name', $rows[0]);
$company = array_search('Company', $rows[0]);
$email = array_search('Email', $rows[0]);

$rows = unset($rows[0]);

$array = array();

foreach ( $rows as $r => $row ) {
    foreach ( $row as $c => $cell ) {

    if ($c == $name) { $array = array( 'name' => $cell ); }
    if ($c == $company) { $array = array( 'company' => $cell ); }
    if ($c == $email) { $array = array( 'email' => $cell ); }
    }

}

Can you give me some suggestions? Thank you

  • 写回答

2条回答 默认 最新

  • dongqin8652 2019-07-22 15:06
    关注

    You can try the below code. It will make header name and value of that dynamic, based on csv file.

    $header = array();
    foreach($array as $key=>$value){
    
        if($key == 0){
            $header = array_values($value);
        }else{
    
            $final_result[]= array_combine($header, array_values($value));
        }
    }
    
    echo "<pre>";
    print_r($final_result);
    

    DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?