仅将值推入数组

我正在使用PHP 7.4.1.


当我跑步时:


<?php


$valArr = array();


$companyArr = array(

    'name' => '',

    'description' => '',

);

array_push($valArr,$companyArr);



$priceArr = array(

    'currentPrice' => '',

    'exch_name' => '',

    'exch_symbol' => '',

);

array_push($valArr,$priceArr);



$otherTrxArr = array(

    'otherTrx' => '',

);

array_push($valArr,$otherTrxArr);


print_r($valArr);

我得到:


Array

(

    [0] => Array

        (

            [name] => 

            [description] => 

        )


    [1] => Array

        (

            [currentPrice] => 

            [exch_name] => 

            [exch_symbol] => 

        )


    [2] => Array

        (

            [otherTrx] => 

        )


)

然而,我只想得到:


Array

(

            [name] => 

            [description] => 

            [currentPrice] => 

            [exch_name] => 

            [exch_symbol] => 

            [otherTrx] => 

)

有什么建议如何array_push()正确使用仅添加新数组中的值吗?


互换的青春
浏览 109回答 2
2回答

largeQ

您还可以使用+合并数组。我自己不使用它,因为我发现它与+使用数组时令人困惑。但这是可能的,而且少几个字符。$valArr&nbsp;=&nbsp;$companyArr&nbsp;+&nbsp;$priceArr&nbsp;+&nbsp;$otherTrxArr;https://3v4l.org/R6EFO

冉冉说

它不是array_push(),它正在按照您的要求进行操作,而是使用array_merge()$valArr = array();$companyArr = array(&nbsp; &nbsp; 'name' => '',&nbsp; &nbsp; 'description' => '',);$priceArr = array(&nbsp; &nbsp; 'currentPrice' => '',&nbsp; &nbsp; 'exch_name' => '',&nbsp; &nbsp; 'exch_symbol' => '',);$otherTrxArr = array(&nbsp; &nbsp; 'otherTrx' => '',);$valArr = array_merge($companyArr, $priceArr, $otherTrxArr);print_r($valArr);结果Array(&nbsp; &nbsp; [name] =>&nbsp;&nbsp; &nbsp; [description] =>&nbsp;&nbsp; &nbsp; [currentPrice] =>&nbsp;&nbsp; &nbsp; [exch_name] =>&nbsp;&nbsp; &nbsp; [exch_symbol] =>&nbsp;&nbsp; &nbsp; [otherTrx] =>&nbsp;)
打开App,查看更多内容
随时随地看视频慕课网APP