Bring multi-dimensional array down (unnest) one level - php

Althoug this works well enough, I am curious if anyone knows of a prettier way of doing this as this situation seems to come up quite often.
<?php
//Initialy, data is nested up in $some_array[0] ...
$some_array = array(array('somevar' => "someValue", "someOtherVar" => "someOtherValue"));
print_r($some_array);
Array ( [0] => Array ( [somevar] => someValue [someOtherVar] => someOtherValue ) )
// Could the following line be achieved a more elegant fashion?
$some_array = $some_array[0];
print_r($some_array);
// Prints the intended result:
Array ( [somevar] => someValue [someOtherVar] => someOtherValue )
Does anyone know of a way to achieve this with a native function or in a more elegant fashion?
Thanks!

The native function you're looking for is called reset (Demo):
$some_array = reset($some_array);
For explicit clarification: current is not necessary.

You could use current (explained here), it basically points to the first element in the array and returns it.
To be absolutely sure you get the first element, you should reset your array, like so:
reset($arr)
$firstElement = current($arr)

Related

Get the multidimensional array index value corresponding to other array values

I've a PHP multidimensional array like:
array(
[0] => array("code"=>code1, "value"=>val1, "operation"=>Add),
[1] => array("code"=>code2, "value"=>val2, "operation"=>Remove),
[2] => array("code"=>code3, "value"=>val3, "operation"=>Edit)
)
If I know code and value, how can I get the operation array index value corresponding to that entry. Eg: If I pass code1 and val1, then it should return the value Add. I can use foreach(), but I'm looking for some other faster and efficient way to get it.
Can anyone help me? Thanks in advance.
Simple foreach with a break/return when found will be O(n) in worst case, O(1) in best.
Modifying source array as:
array(
'code1:val1' => Add,
'code2:val2' => Remove,
'code3:val3' => Edit
)
will give you O(1) with accessing like $arr['code1:val1'].
Solution, for example, with array_filter will be O(n) always.
just run a foreach. It will be an O(n) search on worst case.
function getOperation($code,$value){
foreach($array as $key => $item){
if($item["code"]===$code && $item["value"] === $value)
return $item["operation"];
}
return;
}

Fast searching approach in multidimensional array

The above searching I want with minimum number of code and with best serach performance.
I want to generate an array from this above array by putting logic like:
ALL "EMA" key values of array should not be allowed to match with "JACKSON" key values. Similarly all "JACKSON" key values of the same array are not allowed to fall in any value of "EMA" key. So the resulting array would be like shown below:
Array
(
[0] => Array
(
[EMA] => A
[JACKSON] => B
)
[2] => Array
(
[EMA] => D
[JACKSON] => E
)
)
I want to know the best approach with lesser code to achieve this. The method I have used seems so lengthy. I want a shorter and robust approach.
I think this might be a solution:
$emas = array();
$jacksons = array();
foreach($array as $element){
$emas[] = $element['EMA'];
$jacksons[] = $element['JACKSON'];
}
//array_intersect returns the common values in the arrays as an array
if(!empty(array_intersect($emas, $jacksons))){
echo 'array is invalid!';
}

How to access an un-keyed element of an array?

I have an array that comes from a CMS, which means I can't change how it comes to me. The array is named $master_menu; this is the print_r:
Array
(
[A] => Array
(
[ ] => Appetizer
[PROD] => Array
(
[AC] => Order Anchovies
[AL] => Side Alfredo Sauce
[AO] => Add On
)
)
)
I have a variable called $class that contains 'A'. I know I can get at the entire A sub-array like this:
$master_menu[$class]
and I could get at the PROD sub-array like this:
$master_menu[$class]['PROD']
But how can I just get the value in the sub-array without a key (value is Appetizer in this sample)? I've tried $master_menu[$class][0], but obviously that doesn't work because there isn't a sub-array with a zero index.
The empty index is a space $master_menu["A"][" "]. Try using var_dump instead of print_r, it has more details.
There's no such thing as an element without a key. Maybe the key is " " ? I think that'd be consistent with your print_r output.
It looks like print_r gave you a space as an index. Try:
$master_menu[$class][" "]
You can use array_values and parse that out.
Edit: It looks like you might be able to access the empty key ' '... perhaps $master_menu[$class][' '].. just a thought as I'm not sure the exact output.

Array confusion with square brackets

I am using an API which has a lot of data inside lots of arrays which as you may know can be quite confusing.I am relatively new to API's and this one in particular has no documentation.
My code below is grabbing the recent_games() function which is pulling the whole API then I am using foreach loops to get inside the data.
$games = $player->recent_games();
foreach($games['gameStatistics']['array'] as $key => $gameStatistic) {
$game_date[strtotime($gameStatistic['createDate'])] = $gameStatistic;
}
// order data
krsort($game_date);
foreach ($game_date as $game => $data) {
$statistics[$data] = $data['statistics'];
}
I am getting errors such as illegal offset for:
$statistics[$data] = $data['statistics'];
Is there a way to continue down the nesting of arrays ($game_date) to get to the data that I need?
Let me know if you need more info.
Thanks
EDIT more info:
The first foreach loop at the top loops a unix timestamp key per game. Looks like this:
[1370947566] => Array
(
[skinName] => Skin_name
[ranked] => 1
[statistics] => Array
(
[array] => Array
(
[0] => Array
(
[statType] => stat_data
[value] => 1234
)
[1] => Array
(
[statType] => stat_data
[value] => 1234
)
As you can see its quite nested but I am trying to get to the individual statistics array. I hope that helps?
$statistics[$data] = $data['statistics'];
There is absolutely no way this line is correct.
The right hand side uses $data as if it were an array, indexing into it. The left hand side uses $data as a key into an array. Since the only valid types for keys are strings and integers, $data cannot satisfy the requirements of both expressions at the same time -- it cannot be an array and a string or integer.
It's obvious from the error message that $data is in fact an array, so using it as $staticstics[$data] is wrong. What do you want $statistics to be?

PHP built in array function

Lets say I end up with an array like such:
Array ( [0] => Array ( [0] => user
[1] => pass
)
)
maybe as a result of passing an array through a function and using func_get_args()
In this case, I would want to get rid of the initial array, so I just end up with:
Array ( [0] => user
[1] => pass
)
I know I could make a function to accomplish this, and push each element into a new array, however, is there some built in functionality with PHP that can pull this off?
$new_array = $old_array[0];
...
array_pop() will pop the last (first, if only 1 is present) element.
Just take the value of the first element of the "outer" array.
I would recommend array_shift as it removes and returns the first element off of the beginning of the array.

Categories