将一个数组中的某些值与另一个数组中的值组合在一起

时间:2015-02-01 15:52:22

标签: php arrays foreach

我想将lt_中包含前缀$url的值与$color中的值相结合,并创建一个新数组$new。数组$url$color都会存储接下来36小时的值:

print_r($url);

输出

 Array(
     [0]  => "http://example.com/color/green.png",
     [1]  => "http://example.com/color/lt_green.png",
     [2]  => "http://example.com/color/lt_blue.png",
     [3]  => "http://example.com/color/blue.png",
     [4]  => "http://example.com/color/blue.png",
     [5]  => "http://example.com/color/yellow.png",
     ..
     [35] => "http://example.com/color/lt_blue.png",
     );

print_r($color);

输出

Array(
     [0]  => "Green",
     [1]  => "Green",
     [2]  => "Blue",
     [3]  => "Blue",
     [4]  => "Blue",
     [5]  => "Yellow",
     ...
     [35] => "Blue",
     );

我已设法在lt_中找到字符串部分$url并获取$new中的键,但如何添加" Light" (或lt_)到$color中的相应值以填充$new

$new = array(
     [0]  => "Green",
     [1]  => "Light Green",
     [2]  => "Light Blue",
     [3]  => "Blue",
     [4]  => "Blue",
     [5]  => "Yellow",
     ...
     [35] => "Light Blue",
 );

我设法创建了一个只包含值为lt_的键的数组:

$lt = 'lt_';
foreach($url as $key1=>$value1)
{
  foreach($color as $key2=>$value2)
  {
      if (strpos($value1,$lt) !== false)
      {
          $new[$key1] = array();
      }
  }
}

1 个答案:

答案 0 :(得分:1)

如果两个数组的大小相同且索引对应,您可以根据条件迭代并添加带有前缀或不带前缀的颜色:

$arr = Array("http://example.com/color/green.png",
    "http://example.com/color/lt_green.png",
    "http://example.com/color/lt_blue.png",
    "http://example.com/color/blue.png",
    "http://example.com/color/blue.png",
    "http://example.com/color/yellow.png",);

$arr2 = Array(
    "Green",
    "Green",
    "Blue",
    "Blue",
    "Blue",
    "Yellow",);

$new = array();
for ($i = 0; $i < count($arr2); $i += 1) {
    (strpos($arr[$i], 'lt_') !== false) ?
                    $new[] = "Light " . $arr2[$i] :
                    $new[] = $arr2[$i];
}
print_r($new);