Loop into a multidimensional array in PHP - php

I have this array in PHP:
array(
"name" => "Cherry",
"desc" => "I'm a cherry.",
"keys" => array(
"Africa",
"India",
"America"
),
"pict" => "image1.png",
)
And I want to loop into this and between keys to display to countries/continents.
This is what I have already tried:
foreach($details as $detail) {
foreach($keys as $key) {
echo $key;
}
}

In case if you want to get other values in array along with countries:
<?php
$details = array(
"name" => "Cherry",
"desc" => "I'm a cherry.",
"keys" => array(
"Africa",
"India",
"America"
),
"pict" => "image1.png",
);
foreach( $details as $key => $detail ) {
if( is_array( $detail ) && $key == 'keys' ) {
foreach( $detail as $country ) {
echo $country;
}
} else {
echo $detail;
}
}
?>

Related

Add elements to an array to be used in another array

I have the following code:
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => array( "usa", "canada" )
)
)
) );
I also have a loop above to identify all of the "terms" like this:
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
echo $term_single->slug; //do something here
}
I'd like to dynamically replace "usa" and "canada" with the results from my foreach loop. How can I do that?
You should do something like that
function getTermsForQuery($post) {
$result = [];
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
$result[] = $term_single->slug; //do something here
}
return $result;
}
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => getTermsForQuery($post)
)
)
) );
Without foreach Loop
$term_list = get_the_terms($post->ID,$taxonomy);
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => $term_list
)
)
) );
With foreach loop
$term_list = get_the_terms($post->ID,$taxonomy);
foreach($term_list as $term_single) {
$cat_terms[] = $term_single;
}
query_posts( array(
"tax_query" => array(
array(
"taxonomy" => "country",
"field" => "slug",
"terms" => $cat_terms
)
)
) );
I have create 3 arrays then fill each one and insert to another.
//for loop, store the values that you want
$subArray2 = array();
for($row = 0;$row < 3;$row++){
$subArray2[$row] = "Value_$row";
}
$subArray1 = array("taxonomy" => "country","field" => "slug","terms" => $subArray2);
$arr = array("tax_query" => $subArray1);
//var_dump($arr);
foreach($arr as $val){
foreach($val as $val1){
if(is_array($val1)){
foreach($val1 as $val2){
echo "$val2<br>";
}
}else{
echo $val1 . "<br>";
}
}
}

Preg match array keys

I have it like this:
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin"
);
plus some other data in that same array.
User will select only one of these and what I need is:
Check with preg_match to get all keys that starts with "city_"
find key which has value (it is not empty), take that value
assign it to new key
remove all "city_" keys
add new key to array with the name "chosen_city" which will contain that value
What I tried:
foreach ($data as $key => $value) {
$matches = preg_match('/city_/i', $key);
if ($value != "") {
$newValue = $value;
break;
}
}
$data['chosen_city'] = $newValue;
print_r($data);
This works partially, how can I remove all previous "city_" keys from array in that if statement?
NOTE:
I have other keys in array, and I don't want to remove them as well.
Input array:
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
Expected output:
$data = array(
"chosen_city" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
Thanks.
Please put unset for example code :
$data = array( "City_0" => "London", "City_1" => "Paris", "City_2" => "Lisbon", "City_3" => "Berlin");
foreach($data as $key => $value){
$matches = preg_match('/city_/i', $key);
if($matches && $value != ""){
$newValue = $value;
unset($data[$key]);
}elseif($matches){
unset($data[$key]);
}
}
$data['chosen_city'] = $newValue;
preg_* is somewhat overkill in this instance - you could use strpos and it'd work just as well
However, the question is 'how to I remove the city_* keys', so to do that, just use unset():
foreach($data as $key => $value){
$matches = preg_match('/city_/i', $key);
if($value != ""){
$newValue = $value;
unset($data[$key]); //Remove this item from the array
break;
}
}
$data['chosen_city'] = $newValue;
print_r($data);
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
$value = 'Berlin';
if (array_search($value, $data)) {
$data['chosen_city'] = $value;
foreach ($data as $key=>$val) {
if (stripos($key, 'city_')===0) {
unset($data[$key]);
}
}
}
result:
array(5) {
'distance' =>
string(4) "5 km"
'days' =>
string(1) "7"
'tickets' =>
string(1) "2"
'discount' =>
string(3) "10%"
'chosen_city' =>
string(6) "Berlin"
}
If you use PHP >=5.6, probably you can use (I didn't tested this code)
$city = array_search($value, $data);
if ($city) {
$data['chosen_city'] = $value;
$data = array_filter($data,function($key,$val){return stripos($key,'city_')===false;},ARRAY_FILTER_USE_BOTH);
}

Function to get information from data

I have information on some items:
Actually i have this array:
$datas = array(
array(
'name' => "Banana",
'color' => "yellow",
'scientificName' => "Banana",
'weight' => "300",
'quantity' => "3500",
'origin' => "Africa"
),
array (...)
);
I will need to call this function/array like this:
Example 1
// echo getDatas($what_I_know, "what_I_want");
// Must return yellow.
echo getDatas("Banana", "color");
Example 2
// echo getDatas($what_I_know, "what_I_want");
// Must return 3500.
echo getDatas("yellow", "quantity");
All the keys and data will be unique.
Question
How can I proceed?
You could use a function like this:
# parameters: $datas array, the value you've got, the value you want to find
function getData($datas, $got, $to_find) {
foreach ($datas as $d) {
# check if the value exists in the array
if (array_search($got, $d)) {
# it does! Make sure the property we want is also there
if (in_array($to_find, array_keys($d))) {
return $d[$to_find];
}
else {
return "No value exists for $to_find";
}
}
}
return "No data found for $got.";
}
$datas = array(
array(
'name' => "Banana",
'color' => "yellow",
'scientificName' => "Banana",
'weight' => "300",
'quantity' => "3500",
'origin' => "Africa"
),
array (
'name' => "Apple",
'color' => "red",
'scientificName' => "Apple",
'weight' => "100",
'quantity' => "200",
'origin' => "England"
)
);
echo getData($datas, "Banana", "color") . PHP_EOL;
echo getData($datas, "yellow", "quantity") . PHP_EOL;
echo getData($datas, "red", "weight") . PHP_EOL;
echo getData($datas, "Mongoose", "origin") . PHP_EOL;
Output:
yellow
3500
100
No data found for Mongoose.
This is untested but should work.
foreach( $datas as $dat ) {
foreach( $dat as $k => $d ) {
if ( $what_i_know == $d ) {
return $dat[$what_i_want];
}
}
}

Loop through array grouping indexes by value within that array (PHP)

I wish to create a list of items from an array, grouped by a value within that array.
Take this array:
$people = array(
0 => array(
"Forename" => "Jim",
"Surname" => "Smith"
),
1 => array(
"Forename" => "Mike",
"Surname" => "Johnson"
),
2 => array(
"Forename" => "Kim",
"Surname" => "Smith"
),
3 => array(
"Forename" => "Paul",
"Surname" => "Jones"
)
);
Specifically I'd like to run a foreach on $people, grouping them by unique surname. i.e. the desired output would be:
<select>
<optgroup label="Smith">
<option>Jim</option>
<option>Kim</option>
</optgroup>
<optgroup label="Johnson">
<option>Mike</option>
</optgroup>
<optgroup label="Jones">
<option>Paul</option>
</optgroup>
</select>
I'm struggling to come up with anything vaguely efficient and the Google gods aren't watching over me today :( What's the best approach for such a use-case in PHP?
$surnames = array();
foreach($people as $person) {
$surnames[$person['surname']][] = $person;
}
This code stores all persons in an array grouped by their surnames.
The resulting array:
array(
'smith' => array(
0 => array(
"Forename" => "Jim",
"Surname" => "Smith"
),
1 => array(
"Forename" => "Kim",
"Surname" => "Smith"
)
),
'jones' => array(
0 => array(
"Forename" => "Paul",
"Surname" => "Jones"
)
)
)
I would do this way:
$grouped = array();
foreach ($people as $p){
if (!array_key_exist($p["Surname"], $grouped)){
$grouped[$p["Surname"]] = array();
}
$grouped[$p["Surname"]][] = $p;
}
I've added one more duplicate person:
....
4 => array
(
"Forename" => "Kim",
"Surname" => "Smith"
)
);
this is how you filter array :
$uniqueNames = array();
foreach($people as $person)
{
$uniqueNames[$person['Surname']][] = $person['Forename'];
}
if however you also need Forename to be unique, you can do it like this:
$uniqueNames = array_map
(
function($arrayItem)
{
if (is_array($arrayItem))
{
return array_unique($arrayItem);
}
}
, $uniqueNames
);
Also I've made some easy functions to generate html code:
function htmlSelect($name, $optionsData, $selectedItem = null)
{
$str = "\n<select name='$name' id='select-$name'>";
foreach ($optionsData as $k => $value_s)
{
if(is_array($value_s))
{
$str .= htmlOptgroup($k, $value_s);
}
else
{
$selected = ($selectedItem && $selectedItem == $k);
$str .= "\n\t".htmlOption($value_s, $k, $selected);
}
}
$str .= "\n</select>";
return $str;
}
function htmlOptgroup($label, $optionsData, $selectedItem = null)
{
$str = "\n\t<optgroup label='$label'>";
foreach ($optionsData as $k => $value)
{
$selected = ($selectedItem && $selectedItem == $k);
$str .= "\n\t\t".htmlOption($value, $k, $selected);
}
$str .= "\n\t</optgroup>";
return $str;
}
function htmlOption($display, $value, $selected = false)
{
$selectedStr = $selected ? " selected='selected'" : "" ;
return "<option$selectedStr value='$value'>$display</option>";
}
these functions can easily move to static class for html.
finally you call:
echo htmlSelect('unique-surnames', $uniqueNames);
I swear when I started there was no any answers :d

Not getting array all values using php

I have this following array
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
echo $question[$k]['name'][$i];
$i++;
}
But my output is only
aaaccc
I am missing the value bbb
You need to iterate the inner 'name' arrays - you could use a nested foreach loop:
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
foreach($question as $quest)
{
foreach($quest['name'] as $val)
{
echo $val;
}
}
you should loop though like so
foreach($question as $q)
{
foreach($q['name'] as $v)
{
echo $v;
}
}
in foreach you don't need a counter $i, it's for while() or for()
you array is two dimensional so you need 2 foreach
Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.
$questions = [
'ques_15' => ['name' => ['aaa']],
'ques_16' => ['name' => ['bbb', 'ccc']]
];
array_map(function($a){
foreach ($a['name'] as $v) echo $v;
}, $questions);

Categories