在循环分隔字符串数组时用两组值填充数组

问题描述 投票:0回答:2

我有一个由竖线分隔的字符串组成的平面数组:

Array
(
    [0] => style1|000000
    [1] => style2|ff6600
)

我像这样迭代数据:

foreach ($styles as $key => $value) {
    $sort_values[] = explode('|', $value);
}

print_r($sort_values)
显示:

Array
(
    [0] => Array
        (
            [0] => style1
            [1] => 000000
        )
    [1] => Array
        (
            [0] => style2
            [1] => ff6600
        )
)

我实际上想要一个具有关联第一级键的转置结构:

Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
        )
    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
        )
)
php arrays grouping text-parsing delimited
2个回答
5
投票

假设您的输入数组看起来像

array('style1|000000','style2|ff6600', 'style3|22ff22')

你的循环中需要更多的逻辑。

// Initialize output array with an empty styles subarray and a links subarray
$out = array('styles'=>array(), 'links'=>array());
foreach ($styles as $key=>$value) {
   // Loop over and split on the |
   list($style, $link) = explode("|", $value);
   // And append the two resultant values to their respective subarrays via []
   $out['styles'][] = $style;
   $out['links'][] = $link;

   // list() is a useful construct for producing readable results with small arrays,
   // but I could also have used an array to receive the 
   // results of explode()
   // $split = explode("|", $value);
   // $out['styles'][] = $split[0];
   // $out['links'][] = $split[1];

}
print_r($out);

// Prints:
Array
(
    [styles] => Array
        (
            [0] => style1
            [1] => style2
            [2] => style3
        )

    [links] => Array
        (
            [0] => 000000
            [1] => ff6600
            [2] => 22ff22
        )

)

0
投票

您可以使用

explode()
sscanf()
来解析这些用竖线分隔的字符串。

代码:(演示)(w/爆炸()

$result = [];
foreach ($array as $v) {
    sscanf($v, '%[^|]|%s', $result['style'][], $result['links'][]);
    // [$result['style'][], $result['links'][]] = explode('|', $v);
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.