如何为数组中的单个用户分配多个值?

时间:2016-04-05 11:36:00

标签: php arrays

我有两组数组填充了值。一个是另一个的两倍。我需要使用PHP为其他数组中的单个用户分配多组值。

我在解释下面的情景:

$user=['Raj','Rahul','Scot','Virat'];

$value=['1','2','3','4','5','6','7','8']

在这里,我需要为循环中的每个用户分配2个$value数组值。输出应该是这样的:

'Raj'->1,2
'Rahul'->3,4
'Scot'->5,6
'Virat'->7,8

我该怎么做?

7 个答案:

答案 0 :(得分:0)

你可以这样做:

$user=['Raj','Rahul','Scot','Virat'];
$value=['1','2','3','4','5','6','7','8'];

$output = [];
foreach($user as $key => $name){
   $output[$name] = [$value[$key*2], $value[$key*2 + 1]];
}
print_r($output); // <-- you will have here your array.

答案 1 :(得分:0)

你可以试试这个 -

$user=['Raj','Rahul','Scot','Virat'];

$value=['1','2','3','4','5','6','7','8'];

## generate , separated values from every 2 elements in $value array
$temp = array_chunk($value, 2); // Generate array chunks with 2 elements in the same order
$temp = array_map(function($v) {
    return implode(',', $v); // implode them with comma
}, $temp);

## Combine the user array (as key) && generated $temp array (as values)
$new = array_combine($user, $temp);

var_dump($new);

<强>输出

array(4) {
  ["Raj"]=>
  string(3) "1,2"
  ["Rahul"]=>
  string(3) "3,4"
  ["Scot"]=>
  string(3) "5,6"
  ["Virat"]=>
  string(3) "7,8"
}

如果您不需要,个分隔值,array_map功能可以替换为array_chunk($value, 2)

Fiddle

答案 2 :(得分:0)

你可以试试这个

if ( count($value) !== (2*count($user) ) {
    print 'incorrect size';
}
else {
    $result = array(),
    for ($i=0, $j=0 ; $i<count($user) ; $i++, $j+=2) {
        $result[$user[$i]] = sprintf('%s,%s', $value[$j], $value[$j+1]);
    }
}

答案 3 :(得分:0)

您只需使用array_chunkarray_walk,如下所示

$result = [];
$chunked_array = array_chunk($value, 2);
array_walk($chunked_array,function($v,$k) use (&$result,$user) {
    $result[$user[$k]] = implode(',',$v);
});
print_r($result);

或者您可以像{/ p>一样使用for循环

$result = [];
$count = count($value);
$j = 0;
for($i = 0; $i < $count; $i += 2){
    if(isset($user[$j]))
        $result[$user[$j++]] = $value[$i].",".$value[$i+1];
}
print_r($result);

答案 4 :(得分:0)

$user=['Raj','Rahul','Scot','Virat'];
$value=['1','2','3','4','5','6','7','8'];

$output = [];
foreach($user as $key => $name){
 $output[$name] = $value[$key*2].",". $value[$key*2 + 1];
 }
echo "<pre>";
print_r($output); 

答案 5 :(得分:0)

$user = ['Raj','Rahul','Scot','Virat'];
$values = ['1','2','3','4','5','6','7','8'];
$final = array();
foreach($user as $key => $content ){
    $final[$content] = array($values[$key*2],$values[($key*2)+1]);
}

答案 6 :(得分:0)

如果结果需要是多维数组,那么只需组合用户和分块值:

$result = array_combine($user, array_chunk($value, 2));

如果它需要是以逗号分隔的列表,那么除了将implode()映射到每个内部数组之外,执行相同的操作:

$result = array_combine($user,
                        array_map(function($v) { return implode(',', $v); },
                                  array_chunk($value, 2)));