PHP: Handle only parents on array - php

I need to do "foreach" action only for the highest parent nodes in my PHP array.
In this example I would like to get echo of the family lastnames...
$families = array(
'Brooks' => array(
'John',
'Ilsa',
),
'Hilberts' => array(
'Peter',
'Heidy',
));
foreach($families as $family){
// do some action that will return only "Brooks,Hilbers"
// not "Brooks,John,Ilsa,Hilbers,Peter,Heidy,Brooks,John,Ilsa,Hilberts,Peter,Heidy"
}
Is is handable, or should I define the array differently? Thank you very much for any positive answer.

You can simply return the key of the array (which is the family name):
foreach($families as $key => $family){
echo "FAMILY NAME = ".$key;
}
You can use the foreach just like ($array as $value) or like ($array as $key => $value). When the array is indexed (numerical key) the $key returns the position of the index (0, 1, 2...). When the array is associative (named keys), the $key returns the name of the index (in your example, Brooks, Hilberts, ...)
For more information please see PHP Arrays and Foreach Manual

Related

How to check if array contains certain value for specific key when the parent array is not associative?

I have the following array that contains associative arrays:
array(
[0] => array ("name" => "foo", //more key-value pairs)
[1] => array ("name" => "bar", //more key-value pairs)
[2] => array ("name" => "baz", //more key-value pairs)
)
How can I check if a name exists while iterating over another array of names:
foreach ($list_of_names as $name) {
// does the current name exist in the other array?
}
Is there a way to do it without nesting foreach loop inside the foreach loop?
Your question is a bit vague. I understand that you ask whether it is possible to check if any of the inner arrays contains a given key without using two nested foreach loops.
If so then take a look at this example:
<?php
$data = [
["name-foo" => "foo"],
["name-bar" => "bar"],
["name-baz" => "baz"],
];
$needle = "name-bar";
array_walk($data, function($entry) use ($needle) {
var_dump(
array_key_exists($needle, $entry)
? "$needle exists"
: "$needle does NOT exist"
);
});
The output obviously is:
string(23) "name-bar does NOT exist"
string(15) "name-bar exists"
string(23) "name-bar does NOT exist"
In the end there is no way around having to iterate over all entries in the nested arrays. But you don't have to do that explicitly in the calling scope, you can use the many convenience functions php offers, here array_key_exists(...) for example.
If you just need to know if the name exists, you could extract the name values (using array_column()) and (in this case) using aray_flip() to make it an associative array. This allows you to use isset() inside the loop and not have to do any nested loops.
$data = [
['name' => 'foo'], //more key-value pairs)
['name' => 'bar'], //more key-value pairs)
['name' => 'baz'], //more key-value pairs)
];
$list_of_names = [
'foo',
'bart'
];
$dataNames = array_flip(array_column($data, 'name'));
foreach ($list_of_names as $name) {
if (isset($dataNames[$name])) {
echo "$name exists" . PHP_EOL;
} else {
echo "$name does not exist" . PHP_EOL;
}
}
will show
foo exists
bart does not exist

Working with multidimensional array with PHP

I have this array:
$datas = array(
array(
'id' => '1',
'country' => 'Canada',
'cities' => array(
array(
'city' => 'Montreal',
'lang' => 'french'
),
array(
'city' => 'Ottawa',
'lang' => 'english'
)
)
)
);
Question 1:
How can I get the the country name when I have the id ?
I tried: $datas['id'][1] => 'country'
Question 2:
How can I loop in the cities when I have the id ?
I tried:
foreach ($datas as $data => $info) {
foreach ($info['cities'] as $item) {
echo '<li>'.$item['city'].'</li>';
}
}
Thanks a lot.
You have the ID of the array you want analyse, but your array is structured as a map, meaning that there are no keys in the outer array. You will therefore have to iterate the array first to find the object you are looking for.
While the first approach would be to search for the object that has the ID you are looking for, i suggest you map your arrays with their IDs. To do that, you can use two PHP array functions: array_column and array_combine.
array_column can extract a specific field of each element in an array. Since you have multiple country objects, we want to extract the ID from it to later use it as a key.
array_combine takes two arrays with the same size to create a new associative array. The values of the first array will then be used as keys, while the ones of the second array will be used as values.
$mappedCountries = array_combine(array_column($datas, 'id'), $datas);
Assuming that the key 1 is stored in the variable $key = 1;, you can afterwards use $mappedCountries[$key]['country'] to get the name of the country and $mappedCountries[$key]['cities'] to get the cities, over which you can then iterate.
if there might be many arrays in $datas and you want to find one by id (or some other key) you can do something like this:
function search($datas, $key, $value) {
foreach($datas as $data) {
if ($data[$key] === $value) {
return $data;
}
}
So if you want to find where id = 1
$result = search($datas, 'id', '1');
and then you can get country echo $result['country'] or whatever you need.

Ignore # array keys in php foreach loop

I am trying to loop over certain array keys in drupal, but this is more of a generic php array question.
The array looks something like this...
$form['items'] = array(
#title => 'hello',
0 => array(
#subtitle => 'hello2';
),
1 => array(
#subtitle => 'hello2';
),
#prefix => '<div>hello</div>',
);
As you can see, the keys are a mix of numeric keys and #meta keys.
I am using this...
foreach($form['items'] as $x) {
unset($form['items'][$x]['column1']);
}
But i only want to target the numeric keys, I have tried is_numeric but it returned false.
Can someone tell me how to ignore the other keys? (Ignore #title and #prefix etc)
You want to check the keys, but you are using the value in your foreach. Do the following:
foreach($form['items'] as $key => $value) {
if (is_numeric($key))
unset($form['items'][$key]);
}
Hope I was helpful
Use is_int() rather than is_numberic()
foreach ($input_array as $key => $val) {
if (is_int($key)) {
// do stuff
}
}
Important to note that is_int only works on things that are type integer, meaning string representations are not allowed.

Flip key/value pairs from an existing array into an associate array which allows for keys with multiple values in PHP

I need to basically flip an existing associate array into another associate array. It needs to contain the keys from the previous array as values and the values of the previous array as keys. Also, it needs to be able to contain multiple values for a single key.
Code:
class Owner {
public static function groupOwners($array)
{
//insert code
}
}
$array = array(
"Input.txt" => "Bob",
"Code.py" => "Steve",
"Output.txt" => "Bob"
);
var_dump(Owner::groupOwners($array));
The output generated is to be:
["Bob"] => ["Input.txt, Output.txt"], ["Steve"] => ["Code.py"]
You didn't show an attempt but I'm bored:
foreach($array as $key => $val) {
$result[$val][] = $key;
}

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

Categories