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

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

图片转代码服务由CSDN问答提供 功能建议

我读了一个csv文件并得到了这个数组$ rows

 数组
(
 [0] =>数组
(
 [0] =>名称
 [1] =>公司
 [2] =>电子邮件
 [3] =  > City 
)
 [1] =>数组
(
 [0] => Foo 
 [1] => Foo& co 
 [2] => foo @ mail  .com 
 [3] => NY 
)
 [2] =>数组
(
 [0] => Bar 
 [1] => Bar& co 
 [  2] => bar@mail.com 
 [3] =>拉斯维加斯
)
)
   
 
 

我会尝试将其转换为 通过仅过滤第一个数组中包含的某些字段的关联数组。 结果应该是这个

 数组
(
 [0] =>数组
(
 ['名称'] => Foo 
 [' 公司'] => Foo& co 
 ['电子邮件] => foo@mail.com 
)
 [1] =>数组
(
 ['名称'] =>栏 
 ['Company'] => Bar& co 
 ['Email] => bar@mail.com 
)
)
   
 
 

不幸的是我尝试了各种方法但没有成功。

  $ name = array_search('Name',$ rows [0]); 
 $ company = array_search(' 公司',$ 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);  } 
} 
 
} 
   
 
 

你能给我一些建议吗? 谢谢你

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题