2016-03-03 123 views
0

嗨那裏即時通訊相當新的PHP ...只是在一個家庭作業,我們有這個任務來分離一個數組,其內容..但訣竅是分離內容,並把它在組織內容的新陣列中。將數組內容拆分成另一個數組php

但是,我的新陣列是錯誤的。一個指數應該包含所有名稱爲1串 所有的電話號碼,另一個索引...等

礦顯示器像一個在畫面

有什麼建議?代碼的PIC還附上

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 
+0

好,我會。謝謝 – javaMan1995

+0

我剛剛加了 – javaMan1995

+0

好了,所以這是一個txt文件...每一行都是這樣的...與(:)作爲delim。 – javaMan1995

回答

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 
     ) 

) 
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 
     ) 

) 
+0

但我的目標是有一個單一的數組,每個索引包含特定的數據... [名稱] => ...........包含所有名稱爲1字符串與空格作爲delim然後[手機] => .........所有電話都用空格隔開 – javaMan1995

+0

@ javaMan1995 ahhhhhhhh right。我會盡快更新這個答案 – Darren

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 is s upported PHP> = 5.5

Example