从多维数组中获取值并存储到关联数组中

时间:2011-10-14 08:46:35

标签: php

我希望通过循环以下多维数组将所有员工薪水存储为$ salary数组。

任何人都可以帮助我吗?谢谢!

<?php   
$employees["employee 1"]["name"] = "Dana";
$employees["employee 1"]["title"] = "Owner";
$employees["employee 1"]["salary"] = "$60,000";

$employees["employee 2"]["name"] = "Matt";
$employees["employee 2"]["title"] = "Manager";
$employees["employee 2"]["salary"] = "$40,000";

$employees["employee 3"]["name"] = "Susan";
$employees["employee 3"]["title"] = "Cashier";
$employees["employee 3"]["salary"] = "$30,000";
?>

3 个答案:

答案 0 :(得分:1)

以下代码可以帮助您:

$salary = array();
foreach ($employees as $key => $value) {
  $salary[$key] = $value['salary'];
}

答案 1 :(得分:1)

你可以像下面的代码那样做。

foreach($employees as $key =>$values){
    $emp[$key]['name'] = $values['name'];
    $emp[$key]['sal'] = $values['salary'];
}

echo '<pre>';
print_r($emp);

输出将是:

Array
(
    [employee 1] => Array
        (
            [name] => Dana
            [sal] => $60,000
        )

    [employee 2] => Array
        (
            [name] => Matt
            [sal] => $40,000
        )

    [employee 3] => Array
        (
            [name] => Susan
            [sal] => $30,000
        )

)

谢谢..

答案 2 :(得分:0)

foreach ($employees as $employee) {
  foreach ($employee as $var => $val) {
    $$var[$employee] = $val;
  }
}

然后你应该有三个数组,$name$title$salary