从数组中删除分号分隔的值并添加为新值

时间:2019-03-12 06:41:34

标签: php codeigniter

我对数组中的分号分隔值有疑问。在第10个索引中,有3个名称[Leaf;种子;水果] 1个值。

现在,我需要从第10个索引中删除种子和水果,并将它们压入数组作为41和42索引。在37和39索引中也是一样。

array

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

<?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', )

?>