foreach shuffle or array_rand() from a function from an incl


foreach shuffle or array_rand() from a function from an include file

我有一个变量,它正在从include文件中获取一个数组,我想在另一个文件中使用该数组中的foreach,并让它显示我的数组中的随机id。

这里是一个包含文件中的数组。(来自/products.php)

function get_all() {
$products = array();
$products[101] = array(
    "name" => "Red",
    "img" => "img-101.jpg",
    );
$products[102] = array(
    "name" => "Blue",
    "img" => "img-102.jpg",
    );
$products[103] = array(
    "name" => "Green",
    "img" => "img-103.jpg",
    );
foreach ($products as $product_id => $product) {
    $products[$product_id]["sku"] = $product_id;
}
return $products;
}

(来自display.php)现在我想把products.php中的函数调用成一个变量,并让它通过foreach循环。下面是我的代码。。

 require_once include("products.php");
$random = function get_all();
$shuffle = shuffle($random);
foreach($shuffle as $product) { 
    echo $product["name"];
    echo $product["img"];
}

这是我尝试过的代码,但它不断抛出错误,说变量未定义。

有人能告诉我我在这里做错了什么吗?以及如何修复。

提前感谢

u_mulder向您显示了一个实现错误

更改此

$shuffle = shuffle($random);

到以下

shuffle($random);

注意这个错误,转到手动/洗牌并检查功能签名

bool shuffle ( array &$array )

此函数返回一个布尔值,由于它作为引用传递,将影响数组。剩下的似乎应该工作

尝试使用,

$random = get_all();
shuffle($random);
foreach($random as $product) {
    echo $product["name"];
    echo $product["img"];
}

代替

 $random = function get_all(); 
 $shuffle = shuffle($random);