简体   繁体   中英

PHP Add elements to array

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM