uasort函数中的PHP引用

时间:2016-07-27 12:47:53

标签: php pass-by-reference php-7

我有

$products = array(
        "product1" => [
            "a" => ["total" => 1],
            "b" => ["total" => 3],
            "c" => ["total" => 2],
        ],
        "product2" => [
            "d" => ["total" => 3],
            "f" => ["total" => 2],
            "e" => ["total" => 1],
        ],
        "product3" => [
            "g" => ["total" => 3]
        ],
    );

这些是我的产品和每个仓库的库存(仓库有1件产品1 ......)

我想按库存为每个产品分类每个仓库。 我已经做到了:

foreach ($products as &$stocks) {
        uasort($stocks, function($elmt1, $elmt2) {
            return $elmt2["total"] - $elmt1["total"];
        });
}

我在哪里打印我的新数组:

array(3) {
  ["product1"]=>
  array(3) {
    ["b"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
    ["c"]=>
    array(1) {
      ["total"]=>
      int(2)
    }
    ["a"]=>
    array(1) {
      ["total"]=>
      int(1)
    }
  }
  ["product2"]=>
  array(3) {
    ["d"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
    ["f"]=>
    array(1) {
      ["total"]=>
      int(2)
    }
    ["e"]=>
    array(1) {
      ["total"]=>
      int(1)
    }
  }
  ["product3"]=>
  &array(1) {
    ["g"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
  }
}

它完成了我的工作但是当我仔细观察时,我可以看到"&" char只在其中一个数组中。

为什么?

1 个答案:

答案 0 :(得分:1)

由于$ item的事实 - 对数组的最后一个元素的引用。 你可以做到这一点:

$array = ['a', 'b', 'c'];
foreach ($array as &$item) {

}
foreach ($array as $item) {
    $item = 1;
}

var_dump($array);

输出:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  &int(1)
}

只要你不开始使用$ item,这并不可怕。 最好在不同的功能

中引用作业
$array = ['a', 'b', 'c'];
$test = function () use (&$array) {
    foreach ($array as &$item) {
    }
};
$test();
var_dump($array);

输出:

array(3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}

或试试这个:

$products = array(
    "product1" => [
        "a" => ["total" => 1],
        "b" => ["total" => 3],
        "c" => ["total" => 2],
    ],
    "product2" => [
        "d" => ["total" => 3],
        "f" => ["total" => 2],
        "e" => ["total" => 1],
    ],
    "product3" => [
        "g" => ["total" => 3]
    ],
);

foreach ($products as $key=>$stocks) {
    uasort($products[$key], function($elmt1, $elmt2) {
        return $elmt2["total"] - $elmt1["total"];
    });
}

var_dump($products);

输出:

array(3) {
  ["product1"]=>
  array(3) {
    ["b"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
    ["c"]=>
    array(1) {
      ["total"]=>
      int(2)
    }
    ["a"]=>
    array(1) {
      ["total"]=>
      int(1)
    }
  }
  ["product2"]=>
  array(3) {
    ["d"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
    ["f"]=>
    array(1) {
      ["total"]=>
      int(2)
    }
    ["e"]=>
    array(1) {
      ["total"]=>
      int(1)
    }
  }
  ["product3"]=>
  array(1) {
    ["g"]=>
    array(1) {
      ["total"]=>
      int(3)
    }
  }
}