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条)

报告相同问题?