Acubi
Acubi

Reputation: 2783

get value from multidimensional array and store into associative array

I want to store all employee's salary as an $salary Array by looping the following multiimentional array.

Can anyone help me? Thanks!

<?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";
?>

Upvotes: 0

Views: 713

Answers (3)

Chandresh M
Chandresh M

Reputation: 3838

you can do this like below code.

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

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

Out put will be :

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
        )

)

Thanks..

Upvotes: 1

Tran Dinh Thoai
Tran Dinh Thoai

Reputation: 702

Following code may help you:

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

Upvotes: 1

user827080
user827080

Reputation:

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

And then you should have three arrays, $name, $title, $salary.

Upvotes: 0

Related Questions