结合数组和concat值?

时间:2014-01-15 12:49:25

标签: php foreach

解释起来很复杂,所以这里有一个简单的具体例子:

阵列1:

Array
(
    [4] => bim
    [5] => pow
    [6] => foo 
)

阵列2:

Array
    (
        [n] => Array
            (
                [0] => 1
            )

        [m] => Array
            (
                [0] => 1
                [1] => 2
            )

        [l] => Array
            (
                [0] => 1
                [1] => 4
                [2] => 64
            )

我需要输出数组3,

预计

阵列:

Array
        (
            [bim] => n-1
            [pow] => Array
                (
                    [0] => m-1
                    [1] => m-2
                )

            [foo] => Array
                (
                    [0] => l-1
                    [1] => l-4
                    [2] => l-64
                )

最终回应OUTPUT预期:

bim n-1,pow m-1 m-2,foo l-1 l-4 l-64,

我试过这个,但似乎很可惜:

foreach($array2 as $k1 =>$v1){

            foreach($array2[$k1] as $k => $v){
            $k[] =  $k1.'_'.$v);
             }



foreach($array1 as $res =>$val){

            $val = $array2;

            }

感谢您的帮助, 杰斯

4 个答案:

答案 0 :(得分:2)

接受挑战

<?php

$a = array(
    4 => 'bim', 
    5 => 'pow', 
    6 => 'foo',
);
$b = array(
    'n' => array(1),
    'm' => array(1, 2),
    'l' => array(1, 4, 64),
);

$len = count($a);
$result = array();

$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);

for ($i = 0; $i < $len; $i++) {
    $combined = array();
    $key = $aVals[$i];
    $prefix = $bKeys[$i];
    $items = $bVals[$i];

    foreach ($items as $item) {
        $combined[] = sprintf('%s-%d', $prefix, $item);
    };

    if (count($combined) === 1) {
        $combined = $combined[0];
    }

    $result[$key] = $combined;
}

var_dump($result);

?>

答案 1 :(得分:2)

您的代码可能非常简单。例如,假设数组:

$one = Array
(
    4 => 'bim',
    5 => 'pow',
    6 => 'foo'
);

$two = Array
(
        'n' => Array
            (
                0 => 1
            ),

        'm' => Array
            (
                0 => 1,
                1 => 2
            ),

        'l' => Array
            (
                0 => 1,
                1 => 4,
                2 => 64
            )
);

您可以通过以下方式获得结果:

$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
      (list($twoKey, $twoValue) = each($two)))
{
   $result[$oneValue] = array_map(function($item) use ($twoKey)
   {
      return $twoKey.'-'.$item;
   }, $twoValue);
};

-check this demo注意,上面的代码不会将单元素数组作为单个元素。如果需要,只需添加:

$result = array_map(function($item)
{
   return count($item)>1?$item:array_shift($item);
}, $result);

PHP4>=4.3解决方案的版本,PHP5>=5.0您可以找到here

更新:如果您只需要字符串,请使用this(跨版本):

$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
      (list($twoKey, $twoValue) = each($two)))
{
   $temp = array();
   foreach($twoValue as $item)
   {
       $temp[] = $twoKey.'-'.$item;
   }
   $result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);

答案 2 :(得分:1)

作为问题的解决方案,请尝试执行以下代码段

<?php
 $a=array(4=>'bim',5=>'pow',6=>'foo');
 $b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
 $keys=array_values($a);
 $values=array();
 foreach($b as $key=>$value)
 {
   if(is_array($value) && !empty($value))
   {
 foreach($value as $k=>$val)
 {
    if($key=='n')
    {
        $values[$key]=$key.'-'.$val;
    }
    else
    {
        $values[$key][]=$key.'-'.$val;
    }
  }
 }
}

$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>

答案 3 :(得分:1)

通过阅读代码注释,应该明确背后的逻辑 这是一个demo @ PHPFiddle

//omitted array declarations
$output = array();

//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);

//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
    //if the second array has multiple values at the same index
    //as the first array things will be handled differently
    if(count($vals2[$i]) > 1) {         
        $tempArr = array();     

        //iterating over each element of the second array
        //at the specified index
        foreach($vals2[$i] as $val) {
            //we push each element into the temporary array
            //(in the form of "keyOfArray2-value"
            array_push($tempArr, $keys2[$i] . "-" . $val);
        }

        //finally assign it to our output array
        $output[$val1[$i]] = $tempArr;
    } else {
        //when there is only one sub-element in array2
        //we can assign the output directly, as you don't want an array in this case
        $output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
    }

}

var_dump($output);

输出:

Array ( 
  ["bim"]=> "n-1" 
  ["pow"]=> Array (
    [0]=> "m-1" 
    [1]=> "m-2" 
  ) 
  ["foo"]=> Array ( 
    [0]=> "l-1" 
    [1]=> "l-4" 
    [2]=> "l-64" 
  ) 
)

关于您的最终输出,您可以执行类似

的操作
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
    $final .= $key . " ";
    if(count($value) > 1) {
        $final .= implode($value, " ") .", ";
    } else {
        $final .= $value . ", ";
    }
}

$final = rtrim($final, ", ");

这将回显bim n-1, pow m-1 m-2, foo l-1 l-4 l-64