PHP uasort 函数中的引用

PHP references in uasort function

我有

$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]
        ],
    );

这些是我的产品和每个仓库的库存(仓库 A 有 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)
    }
  }
}

它完成了我的工作,但当我仔细观察时,我只能在一个数组中看到“&”字符。

为什么?

由于 $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)
    }
  }
}