dongtu1357 2014-02-23 20:14
浏览 33
已采纳

在foreach循环中从2个不同的多维数组输出1个数组

I need a little help with multidimensional arrays. I need to output/create an new array from two other arrays in PHP. I know that my example is wrong, but here is an example of what I have that almost works:

 $myarray = array(
      'customid1' = array(
                  name=> 'Tim',
                  address=> '23 Some Address'
                  ),
      'customid2' = array(
                  name=> 'John',
                  address=> 'Another Address'
                  )
 );

 $keys = array();
 $values = array(); 

 foreach($myarray as $key => $keyitem) {
        $getkeys = $myarray[$key]['name'] .'-and-a-string';
        $keys[] = $getkeys;
 } 

 foreach($myarray as $value => $valueitem) {
        $getvalues = 'some-other-text-'. $myarray[$key]['address'];
        $values[] = $getvalues;           
    }

 $newarray = array_combine($keys, $values); 

The code above will get all the keys right, except the values for that key inside the new array. Instead it shows the last value in the array in all of keys. So my print_r results will look like:

Array ( Tim-and-a-string => some-other-text-Another Address 
        John-and-a-string => some-other-text-Another Address 
)

As you can see, 'some-other-text-Another Address' appears on all of them, but the second key 'Tim-and-a-string' needs to have 'some-other-text-23 Some Address' included

  • 写回答

2条回答 默认 最新

  • dqr91899 2014-02-23 20:18
    关注

    It's a very minor error but you are using the wrong variable:

    You are using $key instead of $value in the second foreach().

    $key would be the same as the last key in the loop before since the new foreach loop does not override it.

    This should work:

    $myarray = array(
          'customid1' = array(
                      name=> 'Tim',
                      address=> '23 Some Address'
                      ),
          'customid2' = array(
                      name=> 'John',
                      address=> 'Another Address'
                      )
     );
    
     $keys = array();
     $values = array(); 
    
     foreach($myarray as $key => $keyitem) {
            $getkeys = $myarray[$key]['name'] .'-and-a-string';
            $keys[] = $getkeys;
     } 
    
     foreach($myarray as $value => $valueitem) {
            $getvalues = 'some-other-text-'. $myarray[$value]['address'];
            $values[] = $getvalues;           
        }
    
     $newarray = array_combine($keys, $values); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效