开发者

PHP Add elements to array

开发者 https://www.devze.com 2023-03-28 05:34 出处:网络
The line below commented GOAL creates an error. The error is not displayed (just get a white screen) and I do not have access to php.ini to change the settings. I\'m quite sure the error is something

The line below commented GOAL creates an error. The error is not displayed (just get a white screen) and I do not have access to php.ini to change the settings. I'm quite sure the error is something along the lines of "can not use [] for reading".

How can I get around this? The keys must be preserved and that doesn't seem possible with array_push.

foreach ($invention_values as $value)
        {
            if( array_key_exists($value->field_name, $array) )
            {
                //GOAL but creates error: $array[$value->field_name][] = $value->field_value;
                //works but only with numeric keys
                array_push($array, $value);             
            }

            else $array[$value->field_name] = $value;           
        }

EDIT: code

EDIT2: Actually I think the error is cause I'm dealing 开发者_开发技巧with an object an not an array. What is the object equivalent of

$array[$value->field_name][] = $value ?


Your $array[$value->field_name] is empty, so you can't use [] on it. To initialize it as an array, you have to do the following:

if(!array_key_exists($value->field_name, $array) ){
    $array[$value->field_name] = array();
}
$array[$value->field_name][] = $value->field_value;

It contradicts with what you have in your last line, so you have to decide, do you want $array[$value->field_name] be an array or scalar value.

0

精彩评论

暂无评论...
验证码 换一张
取 消