PHP爆炸和数组

时间:2013-05-07 22:30:31

标签: php arrays explode

我有一个字符串:

clid=7 cid=55164 client_database_id=90507 client_nickname=Leandro client_type=0|clid=9 cid=55164 client_database_id=90507 client_nickname=Leandro1 client_type=0|clid=10 cid=55164 client_database_id=90507 client_nickname=Leandro2 client_type=0

'|'是客户的分隔符。 我需要制作一个像:

这样的数组
echo Client[0]['clid']; //return 7
echo Client[1]['clid']; //return 9

我正在尝试:

$clientList = explode('|', $clientList);
foreach($clientList as $client) {
    $aux[] = explode(' ', $client);
}

此代码将导致:

Array ( [0] => Array ( [0] => clid=7 [1] => cid=55164 [2] => client_database_id=90507 [3] => client_nickname=Leandro [4] => client_type=0 ) [1] => Array ( [0] => clid=9 [1] => cid=55164 [2] => client_database_id=90507 [3] => client_nickname=Leandro1 [4] => client_type=0 ) [2] => Array ( [0] => clid=10 [1] => cid=55164 [2] => client_database_id=90507 [3] => client_nickname=Leandro2 [4] => client_type=0 ) )

它创建了一个客户端数组,但现在我需要在'='中爆炸,但我不能

2 个答案:

答案 0 :(得分:3)

  

但我不能

:)你可以! :

$result = array();
foreach(explode('|', $str) as $record) {
    $r = array();
    foreach(explode(' ', $record) as $field) {
        $assignment = explode('=', $field);
        $r[$assignment[0]] = $assignment[1];
    }   
    $result []= $r; 
}

var_dump($result);

输出:

array(3) {
  [0] =>
  array(5) {
    'clid' =>
    string(1) "7"
    'cid' =>
    string(5) "55164"
    'client_database_id' =>
    string(5) "90507"
    'client_nickname' =>
    string(7) "Leandro"
    'client_type' =>
    string(1) "0"
  }
  [1] =>
  array(5) {
    'clid' =>
    string(1) "9"
    'cid' =>
    string(5) "55164"
    'client_database_id' =>
    string(5) "90507"
    'client_nickname' =>
    string(8) "Leandro1"
    'client_type' =>
    string(1) "0"
  }

  ...

答案 1 :(得分:0)

使用正则表达式来做到这一点......简单易行:

$string = "clid=7 cid=55164 client_database_id=90507 client_nickname=Leandro client_type=0|clid=9 cid=55164 client_database_id=90507 client_nickname=Leandro1 client_type=0|clid=10 cid=55164 client_database_id=90507 client_nickname=Leandro2 client_type=0";
if(preg_match_all("/(clid=[0-9]*)\s*(cid=[0-9]*)\s*(client_database_id=[0-9]*)\s*(client_nickname=\w+)\s*(client_type=[0-9]*)/i", $string, $matches))
{
   print_r($matches);

   //loop through records
   /*foreach($matches as $match)
   {

   }*/
}

未经测试