Retrieve values from given array with same key - php

I have two arrays, which I can either do the simple approach, which is do a For Each loop on each array, and if one way is the method, accept it, or vice-versa, or is it possible to set values in an array with the same key value?
Like:
<?php
$Array = Array('UniqueValue' => 'Key',
'UniqueValue_2' => 'Key',
'DifferentValue' => 'Key_2'); // and etc...
?>
I could probably try trial and error, but another method would be somehow integrating the arrays and only reading the values I need?
Thanks for your guys' time.
ah, quick edit. I feel like someone's going to bring this up, so I read Nested array, get items with same key and I tried, but it's not working for me. It reads only the first value, and I'm not breaking the loop. If you want to see the code I'm working with, I'll gladly add it.
Actually, I found a better way to word this, so!
I need to iterate through each array value with the same key in a For Each loop.
Like so:
ForEach($Array as $Key){ // or $Key => $Value
If($Key == 'Key'){
Echo $Value;
}
}

<?php
$Array = Array(
0 => Array('Test', 'Testing', 'Tester'),
1 => Array('Test2'));
Print_R($Array[0]); // Array ( [0] => Test [1] => Testing [2] => Tester )
?>
Ah, I forgot about nesting arrays. Sorry about that, haha, but for anyone who would possibly need an answer, here you go.

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Build PHP array from query

I'm currently manually building an array.
$this->array_list = array('Alaska' => 'Alaska',
'Amanda' => 'Amanda',
'America' => 'America',
'Anthea' => 'Anthea',
'Arena' => 'Arena',
'Atlantis' => 'Atlantis'
);
I have a database that i can query this list from, My question is how do I create the array with key and value once getting the list from the query? Key and Value will always be the same. Using mysql and codeigniter.
Query DB for list, create two arrays and use combine? Has to be an easier way?
Here is what I ended up doing. Probably not the best way, feel free to give better way to do this.
$sofa_list2 = $this->get_media_model->get_sofas();
foreach ( $sofa_list2 as $k=>$v )
{
$newkey = $sofa_list2[$k]['collection_name'];
$sofa_list2[$k] ["$newkey"] = $sofa_list2[$k] ['collection_name'];
unset($sofa_list2[$k]['collection_name']);
}
$sofa_list2 = call_user_func_array('array_merge', $sofa_list2);

PHP Array - Return specific elements of array and display them on one line

I'm about ready to go crazy with this one. I can't seem to figure out how to print out elements of an array and then put all the results on one line (with a specific output).
Here's my array data (after running it through a foreach statement:
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup00-LogVol00
[disk_capacity] => 15G
[disk_used] => 5.3G
)
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /var
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup01-LogVol00
[disk_capacity] => 107G
[disk_used] => 52G
)
Array
(
[hostname] => server01
[server_id] => 4
[disk_mountpoint] => /opt
[disk_datetime] => 1426395600
[disk_device] => /dev/mapper/VolGroup02-LogVol00
[disk_capacity] => 156G
[disk_used] => 127G
)
Here's my foreach statement:
foreach ($storage_report as $item) {
print_r($item);
}
I've spent a couple of hours trying to wrap my mind around a multi-dementional array as well as looking at some other peoples questions on StackOverflow, but nothing seems to fit what I'm trying to do.
By the way, the array above is actually output from a MySQL query and it returns only one unique hostname, so where it has the same hostname as an element, that is correct (same with the server_id).
I even tried a nested foreach loop and that didn't work well and I got confused again, so I didn't want to post it here.
Basically, with the data above, I want the output to look like:
$disk_mountpoint = $disk_used
With that being said, the ultimate output (if you were to parse what I just wrote), the final output would look like:
/ = 5.3G
/var = 52G
/opt = 127G
I feel like I'm over complicating things and wanted to know if someone could just point me in the right direction and help me out.
Thanks!
Drew
um.. just:
foreach ($storage_report as $item) {
echo $item['disk_mountpoint'] .'='.$item['disk_used'];
}
Yeah man over complication. Can't you just do
foreach ($storage_report as $item) {
echo $item['disk_mountpoint']."=".$item['disk_used'];
}
If it is that I undestand, so:
foreach ($storage_report as $item)
{
if (isset($item['disk_mountpoint']) && isset($item['disk_used']))
{
echo $item['disk_mountpoint'] .'='. $item['disk_used'];
}
}
That will iterate the entire collection and will read the content of each cell only if it is set.

How do I get index of an string array on php?

Lets say I have an multidimensional string array:
.food = array(
'vegetable' => array(
'carrot' => 'blablue',
'potato' => 'bluebla',
'cauliflower' => 'blabla'
),
'Fruit' => array(
'apple' => 'chicken65',
'orange' => 'salsafood',
'pear' => 'lokkulakka'
)
);
is it possible to access the array by using index as numbers, instead of using the name of the key?
So for accessing chicken65 , I will type echo $food[1][0]; I don't want to use numbers as key, because its a big array and its more user-friendly if I use string as key and it will let me do for-loops on advanced level.
You can do foreach loops to achieve much the same thing as a typical for-loop.
foreach ($foods as $key => $value) {
//For the first iteration, $key will equal 'vegetable' and $value will be the array
}
$food[1][0] != $food[1]['apple'], so you cannot use numeric keys in this case.
try
$new_array = array_values($food);
however, variable can't start with .. It should start with $
you may want to try the function array_values but since you are dealing with multidemsional arrays, here is a solution posted by a php programmer
http://www.php.net/manual/en/function.array-values.php#103905
but it would be easier to use foreach instead of for.
You can use array_keys() on the array. The resulting array can be traversed via a for-loop and gives you the associative key.
I will show it to you for the first dimension:
$aTest = array('lol' => 'lolval', 'rofl' => 'roflval');
$aKeys = array_keys($aTest);
$iCnt = count($aKeys);
for($i = 0; $i < $iCnt; ++$i)
{
var_dump($aTest[$aKeys[$i]]);
}
You would need to do this for two dimensions but I would not recommend this. It is actually more obstrusive and slower than most other solutions.
I don't think there is something native to go this route.
And it does seem like you are trying to stretch array use a bit.
You should go OOP on this one.
Create a FoodFamilly object and a Food object in which you can store arrays if necessary and you'll be able to write a nice user-friendly code and add indices if needed.
OOP is almost always the answer :)

access array element by value

array(
[0]
name => 'joe'
size => 'large'
[1]
name => 'bill'
size => 'small'
)
I think i'm being thick, but to get the attributes of an array element if I know the value of one of the keys, I'm first looping through the elements to find the right one.
foreach($array as $item){
if ($item['name'] == 'joe'){
#operations on $item
}
}
I'm aware that this is probably very poor, but I am fairly new and am looking for a way to access this element directly by value. Or do I need the key?
Thanks,
Brandon
If searching for the exact same array it will work, not it you have other values in it:
<?php
$arr = array(
array('name'=>'joe'),
array('name'=>'bob'));
var_dump(array_search(array('name'=>'bob'),$arr));
//works: int(1)
$arr = array(
array('name'=>'joe','a'=>'b'),
array('name'=>'bob','c'=>'d'));
var_dump(array_search(array('name'=>'bob'),$arr));
//fails: bool(false)
?>
If there are other keys, there is no other way then looping as you already do. If you only need to find them by name, and names are unique, consider using them as keys when you create the array:
<?php
$arr = array(
'joe' => array('name'=>'joe','a'=>'b'),
'bob' => array('name'=>'bob','c'=>'d'));
$arr['joe']['a'] = 'bbb';
?>
Try array_search
$key = array_search('joe', $array);
echo $array[$key];
If you need to do operations on name, and name is unique within your array, this would be better:
array(
'joe'=> 'large',
'bill'=> 'small'
);
With multiple attributes:
array(
'joe'=>array('size'=>'large', 'age'=>32),
'bill'=>array('size'=>'small', 'age'=>43)
);
Though here you might want to consider a more OOP approach.
If you must use a numeric key, look at array_search
You can stick to your for loop. There are not big differences between it and other methods – the array has always to be traversed linearly. That said, you can use these functions to find array pairs with a certain value:
array_search, if you're there's only one element with that value.
array_keys, if there may be more than one.

Categories