简体   繁体   中英

How to add element in this Array?

Now here's the code:

$men = array(
    array('name'=>'NO.1', 'age' => 11),
    array('name'=>'NO.2', 'age' => 22),
    array('name'=>'NO.3', 'age' => 33),
);

$result = array();

echo '<pre>';

foreach($men as $value){
    $result[] = $value;
    $result[]['gender'] = 'M';
}
unset($arr1);

var_dump($result);

But seems there's something wrong, what I want to get is...

$result = array(
    array('name'=>'NO.1', 'age' => 11, 'gender' => 'M'),
    array('name'=>'NO.2', 'age' => 22, 'gender' => 'M'),
    array('name'=>'NO.3', 'age' => 33, 'gender' => 'M'),
);

How should I fix it? Anyone can tell me, thank you.

You should do this instead:

foreach($men as $value){
    $value['gender'] = 'M';
    $result[] = $value;
}

Try this :

$men = array(
    array('name'=>'NO.1', 'age' => 11),
    array('name'=>'NO.2', 'age' => 22),
    array('name'=>'NO.3', 'age' => 33),
);

$result = array();

foreach($men as $key=>$value){
    $thisMen = $men[$key];
    $thisMen['gender'] = 'M';
    $result[] = $thisMen;
}

var_dump($result);

You could also avoid the extra $thisMen variable by doing something like

for($i=0;$i<count($men);$i++){
    $result[] = $men[$i];
    $result[$i]["gender"] = 'M';
}

Or, just reference the original array values and change them, as follows

foreach($men as &$thisMen)
    $thisMen["gender"] = 'M';

Shai.

You could do:

$newArray = array();
foreach($men as $value){
    $result[] = $value;
    $result['gender'] = 'M';
    $newArray[] = $result;
}
$men = $newArray;
unset($newArray);
<?php
    $men = array(
        array('name'=>'NO.1', 'age' => 11),
        array('name'=>'NO.2', 'age' => 22),
        array('name'=>'NO.3', 'age' => 33),
    );

    $result = array();

    echo '<pre>';

    foreach($men as $value){
        $result[] = array_merge($value, array('gender' => 'M'));
    }
    unset($arr1);
    var_dump($result);
?>

Instead of

foreach($men as $value){
  $result[] = $value;
  $result[]['gender'] = 'M';
}

use

foreach($men as $value){
  $value['gender'] ='M';
  array_push($result, $value);
}

This will loop through each inner arrays, add the gender field to each of them and push them to the $result array.

With this method, the original $men array remains unchanged.

However, if you wish to change the original array as well, you can add an ampersand ( & ) just before the $value on the foreach loop which will use a reference to the inner arrays over creating a copy. This can be done as follows.

foreach($men as &$value){
  $value['gender'] ='M';
  array_push($result, $value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM