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 找人不需要人工智能回答的gamit解算后做形变分析
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错