将数组内容拆分成另一个数组php

时间:2016-03-03 05:14:59

标签: php arrays project extract explode

嗨那里我非常新的PHP ...只是在做一个功课,我们有这个任务来分离一个有内容的数组..但诀窍是分离内容并把它放在一个新的数组与内容组织的。

然而,我的新阵列是错误的。一个索引应包含1个字符串中的所有名称 所有电话号码等的另一个索引

我的显示就像图片中的那个

有什么建议吗?代码图也附上

so this is the new array

this is the code

<pre>
<?php
$fileName = "c:/wamp/www/datebook";

$line = file($fileName);

print_r($line);

foreach($line as $value)
{
    $newLine[] = explode(":",$value);

}

print_r($newLine);
?>
</pre>

这些是小块,它们总共26个......那是来自记事本

Jon DeLoach:408-253-3122:123 Park St., San Jose, CA 04086:7/25/53:85100
Sir Lancelot:837-835-8257:474 Camelot Boulevard, Bath, WY 28356:5/13/69:24500
Jesse Neal:408-233-8971:45 Rose Terrace, San Francisco, CA 92303:2/3/36:25000

3 个答案:

答案 0 :(得分:1)

你可以试试这个 -

// The indexes to be set to new array [Currently I am assuming, You can change accordingly]
$indexes= array(
    'Name' , 'Phone', 'Address', 'Date', 'Value'
);

$new = array();
// Loop through the indexes array
foreach($indexes as $key => $index) {
    // extract column data & implode them with [,]
    $new[$index] = implode(', ', array_column($newline, $key));
}

array_column 支持 PHP&gt; = 5.5

Example

答案 1 :(得分:1)

    <?php
    $fileName = "c:/wamp/www/datebook";

    $line = file($fileName);

    $newLine= array();
    foreach($line as $va)
    {   
        $new = explode(":",$va);
        $newLine['name'][] = $new[0];
        $newLine['phone'][] = $new[1];
        $newLine['etc'][] = $new[2];
    }
    echo "<pre>";
    print_r($newLine);
    ?>

这将输出

Array
(
    [name] => Array
        (
            [0] => Jon DeLoach
            [1] => Joo Del
        )

    [phone] => Array
        (
            [0] => 408-253-3122
            [1] => 408-253-3122
        )

    [etc] => Array
        (
            [0] => 7/25/53
            [1] => 7/25/53
        )

)

答案 2 :(得分:0)

您需要将它们添加到自己的数组中。

$line = explode("\n", $s);

$newLine = array('name' => '','phone' => ''); // add the rest of the columns.....address,etc
foreach($line as $value)
{
    list($name,$phone,$address,$date,$postcode) = explode(":",$value);

    $newLine['name'] .= (empty($newLine['name'])? $name : " ". $name);
    $newLine['phone'] .= (empty($newLine['phone'])? $phone : " ". $phone);
    // etc
}

并且这将适当地添加它们。

Example只需按ctrl + enter即可运行

它返回一个如下所示的关联数组:

Array
(
    [0] => Array
        (
            [name] => Jon DeLoach
            [phone] => 408-253-3122
            [address] => 123 Park St., San Jose, CA 04086
        )

    [1] => Array
        (
            [name] => Sir Lancelot
            [phone] => 837-835-8257
            [address] => 474 Camelot Boulevard, Bath, WY 28356
        )

    [2] => Array
        (
            [name] => Jesse Neal
            [phone] => 408-233-8971
            [address] => 45 Rose Terrace, San Francisco, CA 92303
        )

)