Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 数组操作_Php_Arrays - Fatal编程技术网

Php 数组操作

Php 数组操作,php,arrays,Php,Arrays,我有一个类似这样的数组 [0] => english [1] => 85 [2] => mathematics [3] => 75 [4] => science [5] => 71 [6] => social [7] => 92 我希望所有索引为偶数的值都作为键,所有索引为奇数的值都作为键。像这样 [english] => 85, [mathematics] => 75 [science] => 71 [social] =>

我有一个类似这样的数组

[0] => english
[1] => 85
[2] => mathematics
[3] => 75
[4] => science
[5] => 71
[6] => social
[7] => 92
我希望所有索引为偶数的值都作为键,所有索引为奇数的值都作为键。像这样

[english] => 85,
[mathematics] => 75
[science] => 71
[social] => 92
有什么好的功能来实现这一点吗?或者你能帮我写代码吗?

类似这样的内容:

<?php

$arr[0] = 'english';
$arr[1] = 85;
$arr[2] = 'mathematics';
$arr[3] = 75;
$arr[4] = 'science';
$arr[5] = 71;
$arr[6] = 'social';
$arr[7] = 92;

for($i=0;$i<count($arr);$i++)
{
        if($i & 1)
                $odd[] = $arr[$i];
        else
                $even[] = $arr[$i];
}

$result = array_combine($even,$odd);

var_dump($result);

?>

一个简单的循环可以做到这一点:

$input = array(
  'english',
  85,
  'mathematics',
  75,
  'science',
  71,
  'social',
  92,
);
$output = array();
for ($i=0; $i<count($input); $i+=2) {
  $output[$input[$i]] = $input[$i+1];
}
print_r($output);
$input=array(
“英语”,
85,
"数学",,
75,
"科学",,
71,
"社会",,
92,
);
$output=array();

对于功能性风格的($i=0;$i),仅用于踢踢(不考虑性能):


使用
array\u chunk
函数的解决方案

$arr = array('english', 85,
         'mathematics', 75,
             'science', 71,
              'social', 92
);

$result = array();
$chunks = array_chunk($arr, 2);
foreach ($chunks as $value) {
  $result[$value[0]] = $value[1];
} 

你能从第一个数组的位置发送php代码吗。。
$odd = function($value) {
    return($value & 1);
};

$even = function($value) {
    return(!($value & 1));
};
$oddArr = array_filter($arr, $odd));
$evenArr = array_filter($arr, $even));    
$ans = array_combine($oddArr,$evenArr);
$arr = array('english', 85,
         'mathematics', 75,
             'science', 71,
              'social', 92
);

$result = array();
$chunks = array_chunk($arr, 2);
foreach ($chunks as $value) {
  $result[$value[0]] = $value[1];
}