PHP - 将数据转换为变量

时间:2014-04-02 00:28:37

标签: php arrays variables

我有这个数组输出:

[0] => Array
    (
        [date] => 2014-04-02
        [0] => 2014-04-02
        [shiftName] => Long Day
        [1] => Long Day
    )

[1] => Array
    (
        [date] => 2014-04-03
        [0] => 2014-04-03
        [shiftName] => Long Day
        [1] => Long Day
    )

[2] => Array
    (
        [date] => 2014-04-04
        [0] => 2014-04-04
        [shiftName] => Long Day
        [1] => Long Day
    )

是否可以将数据设置为变量?

例如:

$date = 2014-04-06;
$shiftname = Long Day;

如果是这样,从结果如何使用循环将其变成这样的表?:

-+--------------------------------------+- 
 | 2014-04-02 | 2014-04-03 | 2014-04-06 |
-+--------------------------------------+-
 | Long Day   | Long Day   | Long Day   |
-+--------------------------------------+-

2 个答案:

答案 0 :(得分:2)

http://ua.php.net/extract应该对您有用。它完全符合您的描述。

可能存在一些警告,其中多个阵列存在相同的键。但这表明变量分配的自动化不可避免地存在缺陷;关于作业的相对具体是很好的。如果您需要提取每个数组,那么您将不得不迭代并为键或其他内容提供前缀以避免冲突。

答案 1 :(得分:1)

如果您希望将Array中的提取信息转换为单个变量,请执行以下操作:

$date = $your_array[0]['date'];
$shiftname = $your_array[0]['shiftName'];

如果要将信息保存到数组中,请执行以下操作:

$your_array[0]['date'] = $date;
$your_array[0]['shiftName'] = $shiftname;

要将其显示为表格,请尝试以下操作:

// Create an empty Array for the dates and one for the shift names
$dates = array(); $shiftNames = array();
// Initiate the table string
$table = "<table>";

// Save each date and shift from your original array into the date or shiftName array    
foreach($your_array as $sub_array) {
    $dates[] = $sub_array['date'];
    $shiftNames[] = $sub_array['shiftName'];
}

// Create a new row in your table
$table .= "<tr>";

// for each date insert a cell into your table and the first row
foreach($dates as $date) {
   $table .= "<td>".$date."</td>";
}

// close the first row open a new row
$table .= "</tr><tr>";

// for each shift name insert a cell into the table and the second row with the shfitName
foreach($shiftNames as $shiftName) {
    $table .= "<td>".$shiftName."</td>";
}

// close the second row and close the table
$table .= "</tr></table>";

// Echo the table to where ever you want it to have
echo $table;
相关问题