【问题标题】:Pushing into a 2 dimensional array in php在php中推入二维数组
【发布时间】:2016-07-16 20:14:13
【问题描述】:

如果我有一个包含 2 个动态值的数组,如下所示:

 $people = array(
    "george" => "smith"
);

我怎样才能在 php 中加入它?

我试过了

array_push($people, "john" => "smith");

编辑:

我已经尝试了评论的内容,但是添加一个新键并不会在数组中创建一个新条目,虽然应该有 3 个,但只有 1 个值..

 $people = array();

foreach ($items as $item){

    $name = $item->getElementsByTagName('name')->item(0);
    $num = $item->getElementsByTagName('number')->item(0);
    $mess = $item->getElementsByTagName('message')->item(0);

    if($name != NULL && $num != NULL && $mess != NULL){
        $people[$num->textContent] = $name->textContent;

    }

}
 var_dump($people);

【问题讨论】:

  • ...什么?你是什​​么意思“推动那个”?你想增加另一个价值吗?
  • 你想推送到哪个数组?给我们一个您尝试过的代码。
  • 名字是动态输入的,所以最终会是 $people = array( "george" => "smith", "george2" => "smith2" );
  • Google php 数组并了解数组的功能。 - 而且你目前演示的数组,不是二维数组,而是一个简单的平面数组。

标签: php


【解决方案1】:

如果新元素有一个定义的键:

$people['newkey'] = 'newvalue';

没有任何定义的键:

$people[] = 'newvalue';

【讨论】:

    【解决方案2】:

    数组推送但没有键

    array_push($people,'mark');
    

    带钥匙

    $people['keytest'] = test;
    

    【讨论】:

      【解决方案3】:

      在这种情况下,array_push 将不起作用,因为没有下一个索引。 你可以做的是:

      $people['new_key'] = 'new_value';
      

      但如果存在,它将用相同的键替换旧值。所以你可以用isset函数来处理它。

      if(isset($people['new_key'])){
          // do some stuff here!
      }
      else{
          $people['new_key'] = 'new_value';
      }
      

      【讨论】:

        【解决方案4】:

        通过使用修复它

        $people[] = array($num->textContent => $name->textContent);
        

        【讨论】:

        • 通过编写上面的代码,你只是改变了$people数组的结构。现在它看起来像:array(array("key1" => "value1"), array("key2","value2"));只是var_dump($people)print_r($people)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-27
        • 2017-01-19
        • 2015-07-15
        相关资源
        最近更新 更多