0

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.

5 Answers 5

3

You should do this instead:

foreach($men as $value){
    $value['gender'] = 'M';
    $result[] = $value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

You could do:

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

Comments

0
<?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);
?>

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.