dongping1922 2017-03-23 10:45
浏览 34
已采纳

使用两个单个数组创建多维数组

I have two arrays as below.

$e which is 
Array
(
    [0] => AL-Alabama
    [1] => AK-Alaska
)

$c which is
Array
(
    [0] => Aerospace: General
    [1] => Agriculture/Forestry/Fish ing/Mining: General
)

I want to create a multidimensional array using above two single arrays. I wrote below code, but just not working.

$mat1=array(array());    
foreach ($e as $ee);             
         {foreach ($c as $cc);    
         {$mat1[$ee][] = $cc;}} 

It gives me an output as below.

Array
(
    [0] => Array
        (
        )

    [AK-Alaska] => Array
        (
            [0] => Agriculture/Forestry/Fish ing/Mining: General
        )

)

whereas my ideal output should be an array with combinations stored such

(AL-Alabama,Aerospace: General), (AL-Alabama,Agriculture/Forestry/Fish ing/Mining: General) and
(AK-Alaska,Aerospace: General), (AK-Alaska,Agriculture/Forestry/Fish ing/Mining: General)

Any help will be highly appreciated.

Thanks

  • 写回答

1条回答 默认 最新

  • dongshuogai2343 2017-03-23 10:53
    关注

    If the thing that $e and $c have in common is the key: this does mean that $c and $e must have the same length.

    <?php
    $c = ['AL-Alabama', 'AK-Alaska'];
    $e = ['Aerospace: General', 'griculture/Forestry/Fish ing/Mining'];
    $new = [];
    
    if (count($c) == count($e)) {
        for ($i=0; $i < count($c); $i++) {
            $new[$c[$i]] = $e[$i];
        }
        var_dump($new);
    } else {
        echo 'error';
    }
    

    edit: i've changed this

    $new[$i] = ['e'=>$e[$i], 'c' => $c[$i]]; 
    

    to

    $new[$c[$i]] = $e[$i];
    

    but both work and have an other output

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计