处理多宗派数组到数组索引为数组

时间:2018-05-14 05:00:58

标签: php multidimensional-array associative-array

我在php中有多维数组这是数组格式我需要在循环中处理这些数据,并希望每个数组的值都是单个时间及其索引。

Array
(
    [name] => Array
        (
            [0] => third.png
            [1] => second.png
            [2] => first.png
        )

    [type] => Array
        (
            [0] => image/png
            [1] => image/png
            [2] => image/png
        )

    [tmp_name] => Array
        (
            [0] => /opt/lampp/temp/phpOPmQcB
            [1] => /opt/lampp/temp/phpk0j1yp
            [2] => /opt/lampp/temp/phpS2mhVd
        )

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

    [size] => Array
        (
            [0] => 179440
            [1] => 102238
            [2] => 75915
        )

)

我想用新索引处理多维数组,例如核心php中的这个多维数组请帮帮我

array(
    Array
   (
    [name] => third.png
    [type] => image/png
    [tmp_name] => /opt/lampp/temp/phpOPmQcB
    [error] => 0
    [size] => 179440
   )
    Array
  (
    [name] => second.png
    [type] => image/png
    [tmp_name] =>/opt/lampp/temp/phpk0j1yp
    [error] => 0
    [size] => 102238
  )
    Array
  (
    [name] => first.png
    [type] => image/png
    [tmp_name] => /opt/lampp/temp/phpS2mhVd
    [error] => 0
    [size] => 75915
  )
)

1 个答案:

答案 0 :(得分:0)

您可以使用array_keys获取数组的键 然后你需要循环其中一个子阵列的计数。我使用$keys变量从第一个子数组中获取计数。

我将一个for和一个foreach嵌套来构建你期望的数组 此方法是动态的,可以使用更大的输入数组,包括子数组和项目数。

$keys = array_keys($arr);
$count = count($arr[$keys[0]]);

for($i = 0; $i<$count; $i++){
    foreach($keys as $val){
        $new[$i][$val] = $arr[$val][$i];
    }
}

var_dump($new);

输出:

array(3) {
      [0]=>
      array(5) {
            ["name"] => "third.png"
            ["type"] => "image/png"
            ["tmp_name"] => "/opt/lampp/temp/phpOPmQcB"
            ["error"] => 0 
            ["size"] => 179440
      }
      [1]=>
      array(5) {
            ["name"] => "second.png"
            ["type"] => "image/png"
            ["tmp_name"] => "/opt/lampp/temp/phpk0j1yp"
            ["error"] => 0
            ["size"] => 102238
      }
      [2]=>
      array(5) {
            ["name"] => "first.png"
            ["type"] => "image/png"
            ["tmp_name"] => "/opt/lampp/temp/phpS2mhVd"
            ["error"] => 0
            ["size"] => 75915
      }
}

https://3v4l.org/4g40N