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

I have an empty array in PHP and some datas i need to push in this empty array.

For each data i have $data->getName(), $data->getValue() and $data->getPosition() so i have :

        foreach($datas as $key => $data){
            array_push($myEmptyArray, array($data->getName() . ":" . $data->getValue() ));
        }

I get something like that :

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

But i need to use ma position attribut, for have something like (if i have respectively 0-0-1 in my position attribut :

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

If i try $myEmptyArray[$data->getPosition()] i have an error "empty array"

Thanks for help !

$myEmptyArray = array();

foreach($datas as $key => $data){
    $myEmptyArray[$data->getPosition()] =  array($data->getName() . ":" . $data->getValue() );
}

use custom keys instead of array_push. After that you can use with these keys. For your situation the kay will be positions.

print_r($myEmptyArray[$position_id]); // get by position id 
$myEmptyArray = array();
$temp_val = '';
$new_val = '';
foreach($datas as $key => $data){
    if(array_key_exists ( $data->getPosition() , $myEmptyArray )){
        $temp_val = $myEmptyArray[$data->getPosition()];
        $new_val = array($data->getName() . ":" . $data->getValue() );
        $myEmptyArray[$data->getPosition()] = $temp_val.','.$new_val;
    }else{
        $myEmptyArray[$data->getPosition()] =  array($data->getName() . ":" . $data->getValue() );
    }
}


print_r($myEmptyArray[$position_id]);

This code will save your record in array and it will not replace your values.

I have the solution :

    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());
    }