将字符串转换为多个字符的关联数组拆分

时间:2013-03-06 11:38:39

标签: php arrays

我有一个以下可能格式的字符串:

"John|Smith,Bob,Bill|Smith“等。

因此,这些是逗号分隔的对,它们本身由|

分开

每个部分(以逗号分隔)可以有1个或2个部分,用|分开。

我想将此转换为关联数组的最佳方法,例如:

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

4 个答案:

答案 0 :(得分: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
        )

)

答案 1 :(得分: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);

?>

请注意,这假设始终至少有一个名字。

答案 2 :(得分: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
        )

)

答案 3 :(得分: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)