php multi-dimensional array help needed - php

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);
}

Related

get me the value of multi dimensional php array with subarrays

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"]

3d nested array foreach statement issue

I have this array written below, and I know it isnt pretty, sorry. I come to this array structure as it is the only way I could think of when dealing with my post request.
$_POST = array("person" => array(
[1] => array("id" => 1, "name" => "bob"),
[2] => array("id" => 2, "name" => "jim")
)
);
I want to be able to pick "name" from certain "id", so below code is what I came up with. In the example below, if person["id"] is equal to 1, retrieve its "name" which is "bob".
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if ($person["id"] == 1) {
echo $person["name"];
}
}
}
}
The problem I am having is as I execute the code.
the result is bobbob,
it seems like the code looped the if statement twice (same as the number of elements in the person array). I know if I put break into the code, then it will solve it, but anyone know why it looped twice? Maybe this will deepen my foreach and array understanding.
There is no need to have third nested loop. Hope this one will be helpful.
Problem: In the third loop you were iterating over Persons: array("id" => 1, "name" => "bob") which have two keys. and you are checking only single static key $person["id"], that's why it was printing twice.
Solution 1:
Try this code snippet here
<?php
ini_set('display_errors', 1);
$POSTData = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($POSTData as $dataSet)
{
foreach ($dataSet as $person)
{
if ($person["id"] == 1)
{
echo $person["name"];
}
}
}
Solution 2:
Alternatively you can try this single line solution.
Try this code snippet here
echo array_column($POSTData["person"],"name","id")[1];//here 1 is the `id` you want.
You must have seen the other answers, and they have already said that you dont need the 3rd loop. but still if you want to keep the third loop.
you can use this code.
foreach ($_POST as $dataSet) {
foreach ($dataSet as $person) {
foreach ($person as $field => $value) {
if($value == 1){
echo $person['name'];
}
}
}
}
No need of third foreach
<?php
$mainArr = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
foreach ($mainArr as $dataSet) {
foreach ($dataSet as $person) {
if ($person["id"] == 1) {
echo $person["name"];
break;
}
}
}
?>
Live demo : https://eval.in/855386
Although it's unclear why you need to do a POST in this fashion, here's how to get "bob" only once:
<?php
$_POST = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
$arr = array_pop($_POST);
foreach($arr as $a) {
if ($a["id"] == 1) {
echo $a["name"];
}
}
Array_pop() is useful for removing the first element of the array whose value is an array itself which looks like this:
array(2) {
[1]=>
array(2) {
["id"]=>
int(1)
["name"]=>
string(3) "bob"
}
[2]=>
array(2) {
["id"]=>
int(2)
["name"]=>
string(3) "jim"
}
}
When the if conditional evaluates as true which occurs only once then the name "bob" displays.
See live code.
Alternatively, you could use a couple of loops as follows:
foreach ($_POST["person"] as $data) {
foreach ($data as $value) {
if ( $value == 1) {
echo $data["name"],"\n";
}
}
}
See demo
As you mentioned, I want to be able to pick name from certain id, : No need of nested looping for that. You can do like this using array_column and array_search :
$data = array("person" => array(
1 => array("id" => 1, "name" => "bob"),
2 => array("id" => 2, "name" => "jim")
)
);
// 1 is id you want to search for
$key = array_search(1, array_column($data['person'], 'id'));
echo $data['person'][$key + 1]['name']; // $key + 1 as you have started array with 1
Output:
bob
with foreach:
foreach ($data as $dataValue) {
foreach ($dataValue as $person) {
if ($person['id'] === 1) {
echo $person["name"];
}
}
}

Obtain specific piece of PHP 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;
}
}
}
}

php get name of array

$shortcodes['video_section'] = array(
'no_preview' => true,
'params' => 'xxx',
'shortcode' => '[sc1][/sc1]',
'popup_title' => __('Video Section', THEME_NAME),
'shortcode_icon' => __('li_video')
);
$shortcodes['image_section'] = array(
'no_preview' => true,
'params' => 'yyy',
'shortcode' => '[sc2][/sc2]',
'popup_title' => __('Image Section', THEME_NAME),
'shortcode_icon' => __('li_image')
);
$shortcodes[] = $th_shortcodes;
How can I retrieve the name of each array and then access to the key and value:
for example I need to loop throught $shortcode and get the array main name: 'image_section' 'video_section'
Then to retrieve the value of some key. I know how to retrieve key and value but really don't understand how to get the name of the declared array. If i do: var_dump($value); I saw the name of the array but how to access to it?
You can use foreach
foreach($shortcodes as $key => $value) {
echo $key // echoes "vide_section" and "image_section"
foreach($value as $innerKey => $innerValue) {
echo $innerKey // echoes 'no_preview', 'params', 'shortcode', 'popup_title', 'shortcode_icon' twice
}
}
Note that $value in this case refers to arrays, you can foreach again to access the inner values.
Use the array_flip function on the array
$array = array_flip($shortcodes);
Yes you can use foreach, where it goes through each item on array, based on creation order.
foreach($shortcodes as $key => $value) {
// $key represents video_section for 1st iteration and image_section for 2nd.
//Here each are array, so you can again iterate over $value and get each item .
foreach($value as $key2 => $value2) {
//here keys are no_preview, params and so on on subsequent iterations.
}
}
There's array_keys():
$keynames = array_keys($shortcodes);
You could foreach throught it:
foreach($shortcodes as $key=>values){ echo $key; }
or flip the values with the case (though this last one I don't recommend), and than foreach through those. But array flip is best to be left alone in this case (though I nice function to keep in the back of your head).

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

Categories