我对数组中的分号分隔值有疑问。在第 10 个索引中,有 3 个名称 [Leaf; 种子; 水果] 在 1 值。
现在,我需要的是从第 10 个索引中删除种子和果实,并将它们作为 41 和 42 索引推送到数组中。在 37 和 39 索引中也是如此。
在此先感谢您的帮助。
我对数组中的分号分隔值有疑问。在第 10 个索引中,有 3 个名称 [Leaf; 种子; 水果] 在 1 值。
现在,我需要的是从第 10 个索引中删除种子和果实,并将它们作为 41 和 42 索引推送到数组中。在 37 和 39 索引中也是如此。
在此先感谢您的帮助。
您可以循环数组并以分号展开。
然后将数组中的值替换为分解后的第一项,其余的与主数组合并。
foreach($arr as $key => $val){
$temp = explode("; ", $val);
$arr[$key] = $temp[0];
$arr = array_merge($arr, array_slice($temp,1));
}
var_dump($arr);
<?php
// Array containing semi-colon space separated items
$plantPartNames = array(
"a",
"b",
"c; d; e",
"f",
"g",
"h; i; j",
"k"
);
// Store additions
$additions = array();
// Loop through array
foreach ($plantPartNames as &$val) {
// Check for semi-colon space
if (strpos($val, "; ") === false) {
continue;
}
// Found so split.
$split = explode("; ", $val);
// Shift the first item off and set to referenced variable
$val = array_shift($split);
// Add remaining to additions
$additions = array_merge($additions, $split);
}
// Add any additions to array
$plantPartNames = array_merge($plantPartNames, $additions);
// Print
var_export($plantPartNames);
// Produces the following:
// array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'f', 4 => 'g', 5 => 'h', 6 => 'k', 7 => 'd', 8 => 'e', 9 => 'i', 10 => 'j', )
?>