How to ungroup an element in an multi-dimentional array?
I have a function that gets users from a MySQL database, the results rows can be 1 or multi开发者_如何学Gople rows.
What annoys me is that when i'm only looking to get 1 result from the db, it returns me a multi-dimentional array like this:
$result = array([0]=>array('foo'=>'bar'))
And makes me write nasty code like:
$e = $result[0]['foo'] // instead of $result['foo']
I'm pretty sure that many people came across this situation, i thought it would be cool if i can check if there is only one row returned and then append to $result
an ungrouped version of it so i can use it when i'm looking for only 1 row. so it'd be like this:
$result = array(
[0] => array('foo'=>'bar'), // will keep the multi-dimentional version
'foo' => 'bar' // and append the ungrouped version of $result here
);
How to do that?
if ( count($result) === 1)
{
$result = $result[0];
}
Sounds to me like something's a little wonky in your API.
If you have a function that can return 1 to n
results from a database, then it should be accessed through array accessors (such as $result[0]['foo']
). Alternatively, you could store the result in a temp var, such as:
$o = $result[0];
print_r($o['foo']);
The problem with doing what you're asking is that you're munging your return data on a special case basis, which is not only confusing to those who may use your code, but it's very error-prone, potentially leaving a user wondering why they can't access the 0th element of $result
.
Functions that return a single element should return a single element. Functions that return multiple elements should return multiple elements (and not have their data changed on special cases).
精彩评论