Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php在数组中的特定位置添加元素_Php_Arrays - Fatal编程技术网

Php在数组中的特定位置添加元素

Php在数组中的特定位置添加元素,php,arrays,Php,Arrays,我在PHP中有一个空数组,需要将一些数据推送到这个空数组中 对于每个数据,我都有$data->getName(),$data->getValue()和$data->getPosition(),所以我有: foreach($datas as $key => $data){ array_push($myEmptyArray, array($data->getName() . ":" . $data->getValue() ));

我在PHP中有一个空数组,需要将一些数据推送到这个空数组中

对于每个数据,我都有
$data->getName()
$data->getValue()
$data->getPosition()
,所以我有:

        foreach($datas as $key => $data){
            array_push($myEmptyArray, array($data->getName() . ":" . $data->getValue() ));
        }
我得到了这样的东西:

[["lastname:andraud"], ["lastname:andro"], ["firstname:clement"]]
但是我需要使用ma
position
attribute,例如(如果我的position attribute中分别有0-0-1:

[["lastname:andraud, lastname:andro"], ["firstname:clement"]]

如果我尝试
$myEmptyArray[$data->getPosition()]
我有一个错误
“空数组”

谢谢你的帮助

$myEmptyArray = array();

foreach($datas as $key => $data){
    $myEmptyArray[$data->getPosition()] =  array($data->getName() . ":" . $data->getValue() );
}
使用自定义键而不是数组_push。之后,您可以使用这些键。根据您的情况,kay将是位置

print_r($myEmptyArray[$position_id]); // get by position id 
此代码将在数组中保存您的记录,并且不会替换您的值。

我有一个解决方案:

    foreach($values as $key => $value){
        $name = $value->getName();

        if(!isset($array[$value->getPosition()])){
            $array[$value->getPosition()] = array();
        }

        array_push($array[$value->getPosition()],  $name . ":" . $value->getValue());
    }

它返回空数组,因为数组中没有任何内容,而您正试图从空数组中获取元素。我想在空数组中添加元素,那么…解决方案是什么?您想要的行为是用“,”连接如果已经设置了索引或使用了关联数组样式?您可以在php中在数组的任何索引处插入元素,但是如果使用计数器在其中循环,则需要执行“isset”。
$myEmptyArray[$data->getPosition()]=array(“name”=>$data->getName(),“value”=>$data->getValue())不,我需要增加价值,而不是每次都替换
    foreach($values as $key => $value){
        $name = $value->getName();

        if(!isset($array[$value->getPosition()])){
            $array[$value->getPosition()] = array();
        }

        array_push($array[$value->getPosition()],  $name . ":" . $value->getValue());
    }