PHP - 使用文本字符串中的键创建数组

时间:2016-08-04 14:54:48

标签: php arrays regex

我有简单的文字字符串,它看起来像那样:

30143*1,30144*2,30145*3,30146*5,30147*5

我必须使用以下结构将此文本字符串转换为数组:

Array ( [0] => Array ( [product] => 30143 [qty] => 1 ) [1] => Array ( [product] => 30144 [qty] => 2 ) [2] => Array ( [product] => 30145 [qty] => 3 ) [3] => Array ( [product] => 30146 [qty] => 4 ) [4] => Array ( [product] => 30147 [qty] => 5 ) )

是否有可能,如果是这样的话?

我发现了这个:

$myString = "9,admin@example.com,8";
$myArray = explode(',', $myString);
print_r($myArray);

但这只是创建没有键的数组,例如,无法使用qty获取*键。

提前致谢!

4 个答案:

答案 0 :(得分:2)

你走了。您需要遍历所有30143*1项。 array_map为你做这份工作。

function getPieces($val) {
    $pieces  = explode('*', $val);
    return ['product' => $pieces[0], 'qty' => $pieces[1]];
}

$str = '30143*1,30144*2,30145*3,30146*5,30147*5';
$result = array_map('getPieces', explode(',', $str));

var_dump($result);

<强>输出:

array (size=5)
  0 => 
    array (size=2)
      'product' => string '30143' (length=5)
      'qty' => string '1' (length=1)
  1 => 
    array (size=2)
      'product' => string '30144' (length=5)
      'qty' => string '2' (length=1)
  2 => 
    array (size=2)
      'product' => string '30145' (length=5)
      'qty' => string '3' (length=1)
  3 => 
    array (size=2)
      'product' => string '30146' (length=5)
      'qty' => string '5' (length=1)
  4 => 
    array (size=2)
      'product' => string '30147' (length=5)
      'qty' => string '5' (length=1)

答案 1 :(得分:2)

这可能是以下方式之一:     

$string = '30143*1,30144*2,30145*3,30146*5,30147*5';

$products = explode(',',$string);
$result = array();
foreach ($products as $productAndQuantity) {
    $result[] = array_combine(array('product', 'qty'), explode('*', $productAndQuantity));
}

var_dump($result);

输出:

array(5) {
  [0]=>
  array(2) {
    ["product"]=>
    string(5) "30143"
    ["qty"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["product"]=>
    string(5) "30144"
    ["qty"]=>
    string(1) "2"
  }
  [2]=>
  array(2) {
    ["product"]=>
    string(5) "30145"
    ["qty"]=>
    string(1) "3"
  }
  [3]=>
  array(2) {
    ["product"]=>
    string(5) "30146"
    ["qty"]=>
    string(1) "5"
  }
  [4]=>
  array(2) {
    ["product"]=>
    string(5) "30147"
    ["qty"]=>
    string(1) "5"
  }
}

答案 2 :(得分:1)

Hooray for regex solutions ...

$str = '30143*1,30144*2,30145*3,30146*5,30147*5';

if (preg_match_all('/(?<product>[^*]+)\*(?<qty>[^,]+),?/', $str, $matches, PREG_SET_ORDER)) {
    $result = array_map(
        function ($match) { return array_intersect_key($match, array_flip(['product', 'qty'])); },
        $matches
    );
    print_r($result);
}

preg_match_all来电已mostly does what you want$matches已经是预期结果的一部分了,它只是有一些array_intersect_key摆脱的其他内容。

答案 3 :(得分:0)

@deceze variant:

preg_match_all('~(?<product>\d+)\*(?<qty>\d+)~', $str, $result, PREG_SET_ORDER);
foreach($result as &$m) { unset($m[0], $m[1], $m[2]); }

print_r($result);