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.
精彩评论