0

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

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

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

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

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

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

4 回答 4

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
        )

)
于 2013-03-06T11:46:48.740 回答
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)
于 2013-03-06T12:03:10.903 回答
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);

?>

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

于 2013-03-06T11:47:46.903 回答
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
        )

)
于 2013-03-06T11:54:27.417 回答