I am having an issue where I am trying to save an ID as an array index, but when I convert the array to json, the ID is appearing as an object and not as an array element.
This is a brief example:
$ID = 1001 ;
$item = [] ;
$item["regional"] = [] ;
$item["regional"][$ID] = $someInfo ; //object
json_encode($item) ;
I am returning the json to my app, and when I look at the json formatting the above lists 1001 as an object:
[0:
{ regional:
{ 1001 :
someInfoA : valueA
someInfoB : valueB
}
}
]
If I change the value of $ID = 0, then it stores the ID as a proper array index - which is what I am needing:
$ID = 0 ;
$item = [] ;
$item["regional"] = [] ;
$item["regional"][$ID] = $someInfo ; //object
json_encode($item) ;
The above now shows ID = 0 as an array index [0]:
[0:
{ regional:
[ 0 :
{
someInfoA : valueA
someInfoB : valueB
}
]
}
]
How can I get the first example to set the array index as 1001 and be treated as an array element versus as an object. I am needing to do this so I can quickly see if that array index element/ID exists to either add to it, or create it then add to it.
If this can't be done, then how can I search a multi-dimensional array/object to return the array index that contains the object value 1001 ?
[0:
{ regional:
[ 0 :
{
ID: 1000
someInfoA : valueA
someInfoB : valueB
}
]
[ 1 :
{
ID: 1001
someInfoA : valueA
someInfoB : valueB
}
]
}
]
$index = array_key_exists($item["regional"],1001) ; // or something like this
var_dump($index) ; // index = 1 ;
ID:1001belongs to without doing a foreach loop.trueas second arg. Also, look at array_column, works on objects also in 7+(array) $item["regional"]syntax, and php.net/manual/en/function.array-search.php may be part of your answer