PHP | Array get both value and key - php

I have a PHP array that looks like that:
$array = Array
(
[teamA] => Array
(
[188555] => 1
)
[teamB] => Array
(
[188560] => 0
)
[status] => Array
(
[0] => on
)
)
In the above example I can use the following code:
echo $array[teamA][188555];
to get the value 1.
The question now, is there a way to get the 188555 in similar way;
The keys teamA, teamB and status are always the same in the array. Alse both teamA and teamB arrays hold always only one record.
So is there a way to get only the key of the first element of the array teamA and teamB?

More simple:
echo key($array['teamA']);
More info

foreach($array as $key=>$value)
{
foreach($value as $k=>$v)
{
echo $k;
}
}
OR use key
echo key($array['teamA']);

echo array_keys($array['teamA'])[0];
Refer this for detailed information from official PHP site.

Use two foreach
foreach($array as $key => $value){
foreach($value as $key1 => $value2){
echo $key1;
}
}
This way, you can scale your application for future use also. If there will be more elements then also it would not break application.

You can use array_flip to exchange keys and values. So array('12345' => 'foo') becomes array('foo' => '12345').
Details about array_flip can be studied here.

I would suggest using list($key, $value) = each($array['teamA']) since the question was for both key and value. You won't be able to get the second or third value of the array without a loop though. You may have to reset the array first if you have changed its iterator in some way.

I suppose the simplest way to do this would be to use array_keys()?
So you'd do:
$teamAKey = array_shift(array_keys($array['TeamA']));
$teamBKey = array_shift(array_keys($array['TeamB']));
Obviously your approach would depend on how many times you intend to do it.
More info about array_keys and array_shift.

Related

Multidimensional array keys to variable

sadly i havent found any solution yet.
I have an multidimensional array which looks like this:
Array
(
[0] => Array
(
[Symbol] => CASY.US
[Position] => 169873920
)
[1] => Array
(
[Symbol] => US500
[Position] => 168037428
) )
Now i want to write the name of the keys of the inner array into variables so that i have these variables with the values:
$col1 = "Symbol"
$col2 = "Position"
How can i achieve that? Somehow with a couple of foreach loops?
Background: After that i want to check if the columns have the right name for a validation.
Thanks in advance!
Loop nested and save the keys to an array with "col" and an integer that you later can (if you really must extract), but I recommend to keep them in the array.
foreach($array as $subarray){
$i = 1;
foreach($subarray as $key => $val){
$keys["col" . $i] = $key;
$i++;
}
break; // no need to keep looping if the array is uniform
}
//if you must:
extract($keys);
https://3v4l.org/ALVtp
If the subarrays are not the same then you need to loop all subarrays and see if the key has already been saved, if not save it else skip it.
$keys =[];
$i = 1;
foreach($array as $subarray){
foreach($subarray as $key => $val){
if(!in_array($key, $keys)){
$keys["col" . $i] = $key;
$i++;
}
}
}
var_dump($keys);
//if you must:
extract($keys);
var_dump($col1, $col2, $col3);
https://3v4l.org/EklPK
Honestly I would do something like this:
$required = array_flip(['Symbol', 'Position']); //flip because I am lazy like that ['Symbol'=>0, 'Position'=>1]
foreach($array as $subarray){
$diff = array_diff_key($required, $subarray);
//prints any keys in $required that are not in $subarray
print_r($diff);
if(!empty($diff)){
//some required keys were missed
}
}
While its not clear how you validate these the reason is as I explained in this comment
it still doesn't solve the problem, as you really have no way to know what the keys will be (if they are not uniform). So with my example foo is $col3 what if I have bar later that's $col4 what if the order is different next time.... they will be different numbers. Sure it's a few what if's but you have no guarantees here.
By dynamically numbering the keys, if the structure of the array ever changes you would have no idea what those dynamic variables contain, and as such no idea how to validate them.
So even if you manage to make this work, if your data ever changes you going to have to re-visit the code.
In any case if your wanting to see if each array contains the keys it needs to, what I put above would be a more sane way to do it.

php: how to get name from object

this might be very simple, and well, yes ... I may not fully understand how objects work, which seems to be the real problem here. So thanks for helping! ^^
I've got an Object that kinda looks like this.
$myobject = Array( [some_random_name] => "Value to that random name" )
Since I'm not sure how those two bits of information are called (sry for that) I will refer to them as "name" and "value". My question is: how do I extract these informations? I need both, the "name" and the "value", so I can store them in two variables ($namevar, $nameval), which should then output something like this:
echo($namevar) = "some_random_name"
echo($nameval) = "Value to that random name"
Thanks.
well, you are using an Array, not an object. in order to get the array keys or values, you could use the following functions: array_values & array_keys.
i could add code snippets etc, but its really straight forward in php's docs:
http://php.net/manual/en/function.array-values.php
http://php.net/manual/en/function.array-keys.php
you could also possibly iterate the array or object (works the same for both), using something like the following code:
foreach($object as $key => $value) { ... }
you can use :
$myobject = [ 'key' => 'value' ];
$key = key($myobject);
$value = $myobject[$key];
echo $key; // key
echo $value; // value
it will return the key value for the current array element
see documentation
or you can use a foreach loop like this:
foreach($myobject as $key => $value) {
$namevar = $key;
$nameval = $value;
}
Basically you are asking how do we get the value of array objects? how do we use them?
These are array objects.
echo $yourObjectname->yourpropertyname;
in your case
echo $myobject->some_random_name;
Example -
$arr = Array (
[0] => stdClass Object (
[name] => 'abc'
);
echo $arr[0]->name;
Object is an instance of class or we can say an medium to use classes properties variable and methods.

Extract each value from an associative array with unknown length and value names

I have an array like:
Array
(
[item1] => value1
[item2] => value
[item3] => value3
)
And I want to extract all the names and values to variables.
But say, I don't know the names of items that the array contains.
I wanna generate variables for each array item with the name of this item name in array to make possible of using this variables later.
The result should look like this:
item_name1 = item_value1
item_name2 = item_value2
item_name3 = item_value3
Seems the foreach loop should be usefull here.
I'm not sure if I understood this.
If you want the key from the array to become a variable with the same name you can use the extract function: http://php.net/manual/en/function.extract.php
Using built-in functions is always faster, but if you need the foreach approach with $$:
foreach ($array as $key=>$val)
{
$$key = $val;
}

Array Order maintaining/reggistering original position (php)

I have an array like this one
$state[1]='FG';
$state[2]='BU';
$state[3]='CA';
...
$state[150]='YT'
What I need is to have the $state array ordered from A to Z and maintain, in some structure, the original order of the array.
Something like:
$state_ordered['BU']=2;
$state_ordered['CA']=3;
and so on.
I have the array in the first form in an include file: which is the most performant way and which is the related structure to use in order to have the best solution?
The include is done at each homepage opening...
Thanks in advance,
A.
Well, you can array_flip the array, thus making 'values' be the original indexes, and then sort it by keys...
$b = array_flip($a);
ksort($b);
then work with $b keys , but the values reflect original order
You want array_flip(), which switches the key and value pairs.
Example #2 from the link:
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
Outputs:
Array
(
[1] => b
[2] => c
)
PHP has quite a few functions for sorting arrays. You could sort your array alphabetically by the values it holds by using asort() and then retrieve the index using array_search()
as such:
?php
$state[1]='FG';
$state[2]='BU';
$state[3]='CA';
asort($state);
$key = array_search('BU',$state);
print $state[$key] . PHP_EOL;
print_r($state);
this will output
BU
Array
(
[2] => BU
[3] => CA
[1] => FG
)
which as you can see keeps the original index values of your array. This does mean however that when you loop over your array without using the index directly, like when you use foreach that you then loop over it in the resorted order:
foreach($state as $key=>$value){
print "$key: $value" . PHP_EOL;
}
2: BU
3: CA
1: FG
You'd need to use ksort on the array first to sort it by index again before getting the regular foreach behaviour that you'd probably want/expect.
ksort($state);
foreach($state as $key=>$value){
print "$key: $value" . PHP_EOL;
}
1: FG
2: BU
3: CA
Looping using a for structure with numeric index values always works correcty of course. Be warned that these functions get passed your array by reference, meaning that they work on the 'live array' and not on a copy, you'll need to make your own copy first if you want one, more info in References Explained.

Change the array KEY to a value from sub array

This is the set of result from my database
print_r($plan);
Array
(
[0] => Array
(
[id] => 2
[subscr_unit] => D
[subscr_period] =>
[subscr_fee] =>
)
[1] => Array
(
[id] => 3
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 90,1000
)
[2] => Array
(
[id] => 32
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 150,1500
)
)
How can I change the $plan[0] to $plan[value_of_id]
Thank You.
This won't do it in-place, but:
$new_plan = array();
foreach ($plan as $item)
{
$new_plan[$item['id']] = $item;
}
This may be a bit late but I've been looking for a solution to the same problem. But since all of the other answers involve loops and are too complicated imho, I've been trying some stuff myself.
The outcome
$items = array_combine(array_column($items, 'id'), $items);
It's as simple as that.
You could also use array_reduce which is generally used for, well, reducing an array. That said it can be used to achieve an array format like you want by simple returning the same items as in the input array but with the required keys.
// Note: Uses anonymous function syntax only available as of PHP 5.3.0
// Could use create_function() or callback to a named function
$plan = array_reduce($plan, function($reduced, $current) {
$reduced[$current['id']] = $current;
return $reduced;
});
Note however, if the paragraph above did not make it clear, this approach is overkill for your individual requirements as outlined in the question. It might prove useful however to readers looking to do a little more with the array than simply changing the keys.
Seeing the code you used to assemble $plan would be helpful, but I'm going assume it was something like this
while ($line = $RES->fetch_assoc()) {
$plan[] = $line;
}
You can simply assign an explicit value while pulling the data from your database, like this:
while ($line = $RES->fetch_assoc()) {
$plan[$line['id']] = $line;
}
This is assuming $RES is the result set from your database query.
In my opinion, there is no simpler or more expressive technique than array_column() with a null second parameter. The null parameter informs the function to retain all elements in each subarray, the new 1st level keys are derived from the column nominated in the third parameter of array_column().
Code: (Demo)
$plan = array_column($plan, null, 'id');
Note: this technique is also commonly used to ensure that all subarrays contain a unique value within the parent array. This occurs because arrays may not contain duplicate keys on the same level. Consequently, if a duplicate value occurs while using array_column(), then previous subarrays will be overwritten by each subsequent occurrence of the same value to be used as the new key.
Demonstration of "data loss" due to new key collision.
$plans = array();
foreach($plan as $item)
{
$plans[$item['id']] = $item;
}
$plans contains the associative array.
This is just a simple solution.
$newplan = array();
foreach($plan as $value) {
$id = $value["id"];
unset($value["id"]);
$newplan[$id] = $value;
}

Categories