将键和值对推入多维数组

时间:2017-07-19 16:42:20

标签: php arrays multidimensional-array

请注意,这不是重复 - 但下面是这些问题的延伸)

like this

PHP array_push one array into another

我正在尝试将array_push转换为多维数组,但希望保留第二个数组的数组键。

示例:

<?php
$samplearray = array(
array('name' => "Joe Bloggs", 'age' => "30", 'sex' => "Male", 'title' => "Mr" ),
array('name' => "Jane Bloggs", 'age' => "30", 'sex' => "Female", 'title' => "Mrs" ),
array('name' => "Little Bloggs", 'age' => "10", 'sex' => "Male", 'title' => "Master" ),    
);

array_push ($samplearray[0],"Inserted Value");

print_r($samplearray);
?>

这个输出是:

array(3) {
  [0]=>
  array(5) {
    ["name"]=>
    string(10) "Joe Bloggs"
    ["age"]=>
    string(2) "30"
    ["sex"]=>
    string(4) "Male"
    ["title"]=>
    string(2) "Mr"
    [0]=>
    string(14) "Inserted Value" <-- INSERTED VALUE
  }
  [1]=>
  array(4) {
    ["name"]=>
    string(11) "Jane Bloggs"
    ["age"]=>
    string(2) "30"
    ["sex"]=>
    string(6) "Female"
    ["title"]=>
    string(3) "Mrs"
  }
  [2]=>
  array(4) {
    ["name"]=>
    string(13) "Little Bloggs"
    ["age"]=>
    string(2) "10"
    ["sex"]=>
    string(4) "Male"
    ["title"]=>
    string(6) "Master"
  }
}

我想插入一个键和值,但是当我尝试时 - 它失败了。可以请你建议

array_push ($samplearray[0]['insertedvalue'],"Inserted Value");

为本地服务器上的插入键返回NULL值,但在PHPfiddle上失败。

2 个答案:

答案 0 :(得分:1)

这就是你要找的东西吗?

        $samplearray = array(
        array('name' => "Joe Bloggs", 'age' => "30", 'sex' => "Male", 'title' => "Mr" ),
        array('name' => "Jane Bloggs", 'age' => "30", 'sex' => "Female", 'title' => "Mrs" ),
        array('name' => "Little Bloggs", 'age' => "10", 'sex' => "Male", 'title' => "Master" ),
    );

    $samplearray[0]['othername'] = 'lalala';
    echo '<pre>';
    print_r($samplearray);

这应该打印:

Array
(
[0] => Array
    (
        [name] => Joe Bloggs
        [age] => 30
        [sex] => Male
        [title] => Mr
        [othername] => lalala
    )

[1] => Array
    (
        [name] => Jane Bloggs
        [age] => 30
        [sex] => Female
        [title] => Mrs
    )

[2] => Array
    (
        [name] => Little Bloggs
        [age] => 10
        [sex] => Male
        [title] => Master
    )

答案 1 :(得分:1)

这一定是你需要的。

$samplearray[0]['insertedvalue'] = "Inserted Value";