2013-03-06 74 views
0

我有以下可能的格式的字符串:字符串轉換爲關聯數組分割在多個字符

"John|Smith,Bob,Bill|Smith「等

因此這些是逗號分隔的,其本身由一個分裂對|

(由逗號deliminated)每個部分可以具有其通過分割1或2份|

我想的最佳方式將其轉換爲一個關聯數組如:

array(
    array(
     'firstname' => "Bill" 
     'lastname' => "Smith" 
    ), 
    array(
     'firstname' => "Bob" 
    ), 
    array(
     'firstname' => "Bill" 
     'lastname' => "Smith" 
    ), 
) 
+1

應該是 「鮑勃」。 – 2013-03-06 11:40:27

回答

0

試試這個:

$test = "John|Smith,Bob,Bill|Smith"; 

$i=0; 
$res = array(); 
foreach(explode(",",$test) as $val){ 
    $vl = explode("|",$val); 
    $res[$i]['firstname'] = $vl[0]; 
    if(isset($vl[1])){ 
     $res[$i]['lastname'] = $vl[0]; 
    } 
    $i++; 
} 

echo "<pre>"; 
print_r($res); 

輸出:

Array 
(
    [0] => Array 
     (
      [firstname] => John 
      [lastname] => John 
     ) 

    [1] => Array 
     (
      [firstname] => Bob 
     ) 

    [2] => Array 
     (
      [firstname] => Bill 
      [lastname] => Bill 
     ) 

) 
0

在這裏看到:http://codepad.org/bQMTkWP9

<?php 

$sInput = "John|Smith,Bob,Bill|Smith"; 

$aFirstExpl = explode(",",$sInput); 
$aOutcome = array(); 
$i = 0; 
foreach($aFirstExpl as $sPair){ 
    $aSecExplode = explode("|",$sPair); 
    $aOutcome[$i]['first'] = $aSecExplode[0]; 
    if(isset($aSecExplode[1])){$aOutcome[$i]['last'] = $aSecExplode[1];} 
$i++; 
} 
print_r($aOutcome); 

?> 

注意,這總是假定至少有一個名字。

0
$result = array(); 
$input = "John|Smith,Bob,Bill|Smith"; 

foreach (explode(',', $input) as $data) { 
    if (false !== strpos($data, '|')) { 
     list($firstname, $lastname) = explode('|', $data, 2); 
     $result[] = array(
      'firstname' => $firstname, 
      'lastname' => $lastname, 
     ); 
    } else { 
     $result[] = array(
      'firstname' => $data, 
     ); 
    } 
} 

print_r($result); 

輸出

Array 
(
    [0] => Array 
     (
      [firstname] => John 
      [lastname] => Smith 
     ) 

    [1] => Array 
     (
      [firstname] => Bob 
     ) 

    [2] => Array 
     (
      [firstname] => Bill 
      [lastname] => Smith 
     ) 

) 
0

你可以做這樣的事情:

$values = "John|Smith,Bob,Bill|Smith"; 

$result = array_map(function($elem) { 
    $parts = explode('|', $elem); 

    $output = array('firstname' => $parts[0]); 

    if (isset($parts[1])) 
    { 
     $output['lastname'] = $parts[1]; 
    } 

    return $output; 

}, explode(',', $values)); 

var_dump($result); 

隨着輸出是:

array 
    0 => 
    array 
     'firstname' => string 'John' (length=4) 
     'lastname' => string 'Smith' (length=5) 
    1 => 
    array 
     'firstname' => string 'Bob' (length=3) 
    2 => 
    array 
     'firstname' => string 'Bill' (length=4) 
     'lastname' => string 'Smith' (length=5)