更改阵列格式

时间:2018-01-18 08:40:52

标签: php arrays explode

我有一个打印出这个值的页面:

"Firstname","Ana","George","Wilson"
"Lastname","Smith","Spencer","Carey"
"Age","18","20","22"

我使用file_get_contents和str_getcsv获取这些值。

$array= str_getcsv($test);

我得到的数组结果是

Array ( [0] =>
"Firstname"
    [1] => 'Ana'
    [2] => 'George'
    [3] => 'Wilson'
"Lastname"
    [4] => 'Smith'
    [5] => 'Spencer'
    [6] => 'Carey'
"Age"
    [7] => 18
    [8] => 20
    [9] => 22
))

无论如何我可以将数组格式改成这个吗?

Array
(
    [0] => Array
        (
            [0] => 'Ana'
            [1] => 'George'
            [2] => 'Wilson'
        )

    [1] => Array
        (
            [0] => 'Smith'
            [1] => 'Spencer'
            [2] => 'Carey'
        )
    [2] => Array
        (
            [0] => 18
            [1] => 20
            [2] => 22
        )
)

3 个答案:

答案 0 :(得分:1)

我建议您使用file()

而不是page-tindel-lawrence.phpfile_get_contents()

如下所示: -

str_getcsv()

答案 1 :(得分:0)

将给定数组更改为指定格式:

$array = ['Firstname' => ['Ana', 'George', 'Wilson'], 'Lastname' => ['Smith', 'Spencer', 'Carey'], 'Age' => [18, 20, 22]];

$new_array = [];
foreach ($array as $key => $value) {
    $new_array[] = $value;
}

print_r($new_array);

Array
(
    [Firstname] => Array
        (
            [0] => Ana
            [1] => George
            [2] => Wilson
        )

    [Lastname] => Array
        (
            [0] => Smith
            [1] => Spencer
            [2] => Carey
        )

    [Age] => Array
        (
            [0] => 18
            [1] => 20
            [2] => 22
        )

)

答案 2 :(得分:0)

试试这个我希望我可以提供帮助:

$array = array(0=> array(
              'firstname' => array(1 => 'Ana', 2 => 'George', 3=>'Wilson'),
               'lastname' => array(4=>'Smith', 5=>'Spencer', 6=> 'Carey'),
                'age' => array(7=>18,8=>20,9=>22)
               ));

 $newArray = array();
 echo "<pre/>";print_r($array);
 foreach($array as $key=>$new){


   foreach($new as $k=>$d){

      $newArray[] = array_values($d);
   }
 }
 echo "</br>New Array Format: </br>";
 echo "<pre/>";print_r($newArray);