2012-10-13 22:51



Note: I should be clear my desire is to do this functionally, in one statement. I can do this easily with loops but that's not what I'm interested in.

I have two arrays: a numeric array of indexes, A, and an associative array, B, of objects O indexed by the elements of array A.

I want to produce an array of O in the order of the elements of A--in other words, map the indexes into real objects, based on the associative array B.

For example:

A = [ 3, 4, 2, 1 ];
B = [ 1=>"one", 2=>"two", 3=>"three", 4=>"four" ]

I want:

[ "three", "four", "two", "one" ]

Also, incidentally I'm also curious to learn what this concept is called. It's kind of like mapping, but specifically involves indexes into another array, as opposed to a function.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doudiewen9435 doudiewen9435 9年前

    NullUserException posted the answer in a comment:

    array_map(function ($v) use ($b) { return $b[$v]; }, $a);

    点赞 评论 复制链接分享
  • dongmi4035 dongmi4035 9年前
    $order = array(3, 4, 2, 1);
    $input = array(1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four');

    Using array_map() (PHP 5.3 >)

    $output = array_map(function($v) use($input) { 
      return $input[$v]; 
    }, $order);

    However, this is essentially the same as doing the following:

    $output = array();
    foreach ($order as $o) {
      $output[] = $input[$o];

    I can't honestly see a shorter way of doing this.

    点赞 评论 复制链接分享
  • duandi1919 duandi1919 9年前

    I am just adding a little bit, if anyone is still interested in using "array_map".

        $A = array( 3, 4, 2, 1);
        $B = array( 1=>"one", 2=>"two", 3=>"three", 4=>"four" );
        print_r($A);echo '<br/>';
        print_r($B);echo '<br/>';
        function matchAtoB($sourceA, $sourceB)
            global $B;
            return $B[$sourceA];
        $O = array_map("matchAtoB", $A, $B);

    So the function can only receive an element of each array at a time (not the whole array) and it will loop/repeat itself automatically until all elements in the array are processed.


    点赞 评论 复制链接分享
  • dongpangfu6322 dongpangfu6322 9年前

    You don't need a loop, you can access the elements right away:

    $three = $b[$a[0]]; // "three"
    $four = $b[$a[1]]; // "four"
    $two = $b[$a[2]]; // "two"
    $one = $b[$a[3]]; // "one"

    You could see this as a 'lazy' or 'just in time' way of accomplishing the same goal, but without the ahead cost of indexing the hash map.

    If you want the array explicitly, without the additional lookup, you will need a loop.

    I'm not sure if this has a name but the combination of a 'datastore' or 'hash map' combined with an ordered array of keys is not an uncommon one.

    点赞 评论 复制链接分享
  • douliang1900 douliang1900 9年前
    $A = array(3, 4, 2, 1);
    $B = array(1=>"one", 2=>"two", 3=>"three", 4=>"four");
    foreach($A as $i) $R[] = $B[$i]; 
    点赞 评论 复制链接分享