php array_push 用于关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8289307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:21:49  来源:igfitidea点击:

array_push for associative arrays

phparraysassociative-arrayarray-push

提问by EnglishAdam

I'm trying to extend an assoc array like this, but PHP doesn't like it.

我正在尝试扩展这样的关联数组,但 PHP 不喜欢它。

I receive this message:

我收到这条消息:

Warning: array_push() expects parameter 1 to be array, null given

Here's my code:

这是我的代码:

$newArray = array();  
foreach ( $array as $key => $value ) { 
    $array[$key + ($value*100)] = $array[$key];
    unset ( $array[$key] );
    array_push ( $newArray [$key], $value );
}
//}
print_r($newArray);

Where did I go wrong?

我哪里做错了?

回答by akDeveloper

This is your problem:

这是你的问题:

$newArray[$key] is null cause $newArray is an empty array and has not yet values.

$newArray[$key] 为空,因为 $newArray 是一个空数组并且还没有值。

You can replace your code, with

你可以用你的代码替换你的代码

array_push( $newArray, $value );

or instead of array_push to use

或代替 array_push 使用

$newArray[$key] = $value;

so you can keep the index of your $key.

这样您就可以保留 $key 的索引。

回答by vineet

I use array_merge prebuilt function for push in array as associative.

我使用 array_merge 预建函数将数组作为关联推入。

For example:-

例如:-

$jsonDataArr=array('fname'=>'xyz','lname'=>'abc');
$pushArr=array("adm_no" => $adm_no,'date'=>$date);
$jsonDataArr = array_merge($jsonDataArr,$pushArr);
print_r($jsonDataArr);//Array ( [fname] => xyz [lname] => abc [adm_no] =>1234 [date] =>'2015-04-22')