I have this array:
static $countryList = array(
["AF" => "Afghanistan"],
["AL" => "Albania"],
["DZ" => "Algeria"],
//many more countries
);
I want to do something like $countryList['DZ'] to get "Algeria"
why those damned sub arrays?
well, some countries must come twice
basically this...
static $countryList = array(
["US" => "USA"],
["AL" => "Albania"],
["DZ" => "Algeria"],
//...
["UB" => "Uganda"],
["US" => "USA"]
);
it's used for a select list
Make another array that's an associative array:
$countryMap = [];
foreach ($countryList as $country) {
foreach ($country as $short => $long) {
$countryMap[$short] = $long;
}
}
Then you can use $countryMap["DZ"]
Related
I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);
I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);
I am trying to get a specific value out of a deeply nested PHP array. I have gotten as far as reaching reaching the array that I need and storing it in a variable. The array looks like this:
Array (
[0] => Array (
[social_channel] => twitter
[link] => testing#twitter.com
)
[1] => Array (
[social_channel] => mail
[link] => hcrosby#testing.edu
)
)
Often times this array will contain numerous values such as facebook links, twitter, instagram and they will always be in different orders based on how the user inputs them. How do I only pull out the email address in this array. I know this is basic but PHP is far from my strong point.
Assuming you've got the following:
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
You'd could loop over each item of the array using a foreach and then use the link array key to get the email address. For example:
foreach ($my_array as $item) {
echo $item['link']; // Or save the item to another array etc.
}
You can use array_map function
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
function getMailArray($array) {
return $array['link'];
}
$result = array_map("getMailArray",$my_array);
Try this:
$arr1 = array(array('social_channel' => 'twitter', 'link' => 'testing#twitter.com'),
array('social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'));
$emailArr = array();
foreach ($arr1 AS $arr) {
$emailArr[] = $arr['link'];
}
print_r($emailArr);
$assoc = [];
foreach($array as $sub){
$assoc[$sub["social_channel"]] = $assoc["link"];
}
The above changes social_channel into a key so that you can search directly like this:
$email = $assoc["email"];
Remember to ensure that the input contains the email field, just to avoid your error.log unnecessarily spammed.
<?php
function retrieveValueFromNestedList(array $nestedList, $expectedKey)
{
$result = null;
foreach($nestedList as $key => $value) {
if($key === $expectedKey) {
$result = $value;
break;
} elseif (is_array($value)){
$result = $this->retrieveValueFromNestedList($value, $expectedKey);
if($result) {
break;
}
}
}
}
I have a multi-dimensional array, and I want to group it by org and then by dept. I have the first level of grouping working:
$groups = array();
foreach($inv_h as $item) {
$groups[$item['org']][] = $item;
}
How do I achieve the second level of grouping?
If I understand you correctly then it's as simple as repeating what you've already done for the second tier of the array:
$groups = array();
foreach($inv_h as $item) {
$groups[$item['org']][$item['dept']][] = $item;
}
That should give you an array that looks like this:
groups = array(
org1 => array(
dept1 => array(results...),
dept2 => array(results...)
),
org2 => array(
dept3 => array(results...),
dept4 => array(results...)
)
)
I've got this array (shortened for this question), and I need to extract the country_code ("AF" and "AL" in this demo) in order to insert the region info into a table based on the country.
How do I get the country code while iterating the array and is this the correct way to do this?
$countries = array("AF" => array("BDS" => "Badakhshan",
"BDG" => "Badghis",
"BGL" => "Baghlan",
"BAL" => "Balkh",
"BAM" => "Bamian",
"DAY" => "Daykondi"),
"AL" => array("BR" => "Berat",
"BU" => "Bulqizë",
"DL" => "Delvinë",
"DV" => "Devoll",
"DI" => "Dibër",
"DR" => "Durrës",
"EL" => "Elbasan",
"FR" => "Fier")
);
foreach ($countries as $country) {
$country_code = $country[]; // How do I get the country code here?
foreach ($country as $region_code => $region_name) {
// insert region info into table
} // foreach ($country as $region_code => $region_name)
} // foreach ($countries as $country)
foreach($countries as $code => $list) {
foreach($list as $rcode => $name) {
}
}
code and rcode will have the two region codes
i Mentioned in my comment, that that was the only way, but, i stand corrected
foreach($countries as $country)
{
$code = array_keys($countries, $country);
$code = $code[0];
}
might get you what you are looking for, super weird way to do it tho, and i dont suggest using it. The first method is better
Your array is setup with key => value pairs, meaning you have a value, and an identifier for that value.
$myArray = array( "Key" => "Value" );
Or, in the case of your code:
$myArray = array( "Country Code" => array( "Region" => "Codes" ) );
If you wish to get the key while looping, use the following syntax:
foreach ( $myArray as $key => $value ) {
echo $key; // "Country Code"
foreach ( $value as $region_key => $region_code ) {
echo $region_key; // Region
}
}
Now you're able to access the identifer with each iteration.
Well, you are using it already in the nested loop:
foreach ($countries as $country_code => $country) {
foreach ($country as $region_code => $region_name) {
// foobar
}
}
The variable $country_code then holds the country code.
while($country = current($countries)){
while($region = current($country)){
echo "region:".$region."(".key($country).")"." country:".key($countries);
next($country);
}
next($countries);
}