简体   繁体   English

将字符串中的项目分成两个数组

[英]Separate items in a string into two arrays

How can I split this string into two arrays in PHP?如何在 PHP 中将此字符串拆分为两个数组? The string may have many items in it.字符串中可能有很多项。

$str = "20x9999,24x65,40x5";

I need to get two arrays from this string:我需要从此字符串中获取两个数组:

$array1 = array(20,24,40);
$array2 = array(9999,65,5);

I've tried many implementations of preg_split, slice, regex.我已经尝试过 preg_split、slice、regex 的许多实现。 I can't get it done... I need help!我无法完成……我需要帮助!

You can explode the string by commas, and then explode each of those values by x , inserting the result values from that into the two arrays:您可以用explode分解字符串,然后用x分解每个值,将结果值插入到两个数组中:

$str = "20x9999,24x65,40x5";
$array1 = array();
$array2 = array();
foreach (explode(',', $str) as $xy) {
    list($x, $y) = explode('x', $xy);
    $array1[] = $x;
    $array2[] = $y;
}

Alternatively, you can usepreg_match_all , matching against the digits either side of the x :或者,您可以使用preg_match_all ,匹配x两侧的数字:

preg_match_all('/(\d+)x(\d+)/', $str, $matches);
$array1 = $matches[1];
$array2 = $matches[2];

In both cases the output is:在这两种情况下,输出都是:

Array
(
    [0] => 20
    [1] => 24
    [2] => 40
)
Array
(
    [0] => 9999
    [1] => 65
    [2] => 5
)

Demo on 3v4l.org 3v4l.org 上的演示

I guess with preg_split , we could do so:我想使用preg_split ,我们可以这样做:

$str = '20x9999,24x65,40x5';

$array1 = $array2 = array();

foreach (preg_split("/,/", $str, -1, PREG_SPLIT_NO_EMPTY) as $key => $value) {
    $val = preg_split("/x/", $value, -1, PREG_SPLIT_NO_EMPTY);
    array_push($array1, $val[0]);
    array_push($array2, $val[1]);
}

var_dump($array1);
var_dump($array2);

Output输出

array(3) {
  [0]=>
  string(2) "20"
  [1]=>
  string(2) "24"
  [2]=>
  string(2) "40"
}
array(3) {
  [0]=>
  string(4) "9999"
  [1]=>
  string(2) "65"
  [2]=>
  string(1) "5"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM