dongyou2279 2016-04-29 18:27
浏览 98
已采纳

从多维数组中获取数组并将值传递给PHP中的变量

This code is supposed to created a multidimensional array, shuffle it, select the first array, and pass the four values to four different variables called $common, $uncommon, $rare, and $superrare.

<?php

//create multidimentional array
$distribution = array
(
array(115, 50, 15, 0),
array(115, 49, 16, 0),
array(115, 48, 17, 0),
array(116, 49, 15, 0),
array(116, 48, 16, 0),
array(116, 47, 17, 0),
array(117, 48, 15, 0),
array(117, 47, 16, 0),
array(117, 46, 17, 0),
array(118, 47, 15, 0),
array(118, 46, 16, 0),
array(118, 45, 17, 0),
array(119, 46, 15, 0),
array(119, 45, 16, 0),
array(119, 44, 17, 0),
array(120, 45, 15, 0),
array(120, 44, 16, 0),
array(120, 43, 17, 0),
);

//shuffle the md-array
shuffle($distribution);

//select first array from $distribution
$slice[] = array_slice($distribution ,0, 1);

//create an array for key values
$cardrarity = array('common', 'uncommon', 'rare', 'superrare');

//combine $cardrarity and $slice
$cardraritycount = array_combine($cardrarity, $slice);

//create a variable for each value in 
foreach ($cardraritycount as $key => $value){
    $$key = $value;
    }
?>

When I view the contents of $slice it looks like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 120
                    [1] => 43
                    [2] => 17
                    [3] => 0
                )

        )

)

When I try and combine $slice with $cardrarity, I get no output when I try and echo the contents. I think my problem is when I'm doing the array slice. Any help would be appreciated.

  • 写回答

3条回答 默认 最新

  • douhoulei4706 2016-04-29 18:35
    关注

    array_slice($distribution, 0, 1) returns a multi-dimensional array. It's a 1-element array whose first element is the first element of $distribution. If you just want the first element of $distribution, use $distribution[0].

    To assign to multiple variables from an array, use an assignment to the list() function.

    So the whole thing should be:

    list($common, $uncommon, $rare, $superrare) = $distribution[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题