我有一个数据集,我想将它转换为一个数组,我只是不知道如何...我已经尝试了几个像preg_replace()与正则表达式和爆炸(),但它不出来我需要它的方式。
所以我的数据集如下所示:
dataCrossID=12345, DeviceID=[ID=1234567] dataCrossID=5678, DeviceID=[ID=7654321] dataCrossID=67899, DeviceID=[ID=87654321]并且数组应如下所示:
$dataSet( [12345] => 1234567, [5678] => 7654321, [67899] => 87654321, )我尝试过正则表达式,但数字有不同长度的事实使我很难。
有人有想法吗?
I have a dataset and I want to conevert it into an array and I just can't figure out how... I've tried a couple things like preg_replace() with regex and explode() but it doesn't come out the way I need it.
So my dataset looks like this:
dataCrossID=12345, DeviceID=[ID=1234567] dataCrossID=5678, DeviceID=[ID=7654321] dataCrossID=67899, DeviceID=[ID=87654321]and the Array should look like this:
$dataSet( [12345] => 1234567, [5678] => 7654321, [67899] => 87654321, )I tried regex but the fact that the numbers got different lenghts makes it hard for me.
Does anyone have an idea?
最满意答案
使用preg_match_all()来标识您需要的文本片段:
$input = <<< E dataCrossID=12345, DeviceID=[ID=1234567] dataCrossID=5678, DeviceID=[ID=7654321] dataCrossID=67899, DeviceID=[ID=87654321] E; preg_match_all('/dataCrossID=(\d+), DeviceID=\[ID=(\d+)\]/', $input, $matches, PREG_SET_ORDER); print_r($matches);$matches的内容是:
Array ( [0] => Array ( [0] => dataCrossID=12345, DeviceID=[ID=1234567] [1] => 12345 [2] => 1234567 ) [1] => Array ( [0] => dataCrossID=5678, DeviceID=[ID=7654321] [1] => 5678 [2] => 7654321 ) [2] => Array ( [0] => dataCrossID=67899, DeviceID=[ID=87654321] [1] => 67899 [2] => 87654321 ) )您现在可以迭代$matches并使用位置1和2处的值作为键和值来将数据提取到所需的数组中:
$output = array_reduce( $matches, function(array $c, array $m) { $c[$m[1]] = $m[2]; return $c; }, array() ); print_r($output);输出是:
Array ( [12345] => 1234567 [5678] => 7654321 [67899] => 87654321 )Use preg_match_all() to identify the pieces of text you need:
$input = <<< E dataCrossID=12345, DeviceID=[ID=1234567] dataCrossID=5678, DeviceID=[ID=7654321] dataCrossID=67899, DeviceID=[ID=87654321] E; preg_match_all('/dataCrossID=(\d+), DeviceID=\[ID=(\d+)\]/', $input, $matches, PREG_SET_ORDER); print_r($matches);The content of $matches is:
Array ( [0] => Array ( [0] => dataCrossID=12345, DeviceID=[ID=1234567] [1] => 12345 [2] => 1234567 ) [1] => Array ( [0] => dataCrossID=5678, DeviceID=[ID=7654321] [1] => 5678 [2] => 7654321 ) [2] => Array ( [0] => dataCrossID=67899, DeviceID=[ID=87654321] [1] => 67899 [2] => 87654321 ) )You can now iterate over $matches and use the values at positions 1 and 2 as keys and values to extract the data into the desired array:
$output = array_reduce( $matches, function(array $c, array $m) { $c[$m[1]] = $m[2]; return $c; }, array() ); print_r($output);The output is:
Array ( [12345] => 1234567 [5678] => 7654321 [67899] => 87654321 )更多推荐
发布评论