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.
Related
I have an array that has been filled with default data as shown below
$arrivals = array(
"source" => "arrivals",
"data" => array(
0 => array("flight"=>"000","scheduled"=>"0000","city"=>"Geneva","airline"=>"UAL","gate"=>"A00","status"=>"1","remarks"=>"BOARDING"),
1 => array("flight"=>rand(1,2000),"scheduled"=>randomTime(),"city"=>"Baltimore","airline"=>randomAirline(),"gate"=>"A7","status"=>"0","remarks"=>"")
)
);
Now i want to create the same array with data from a table in a loop using the same identifiers such as 'city' but with variable names .
The other part is that the first part of 'data' array is a number which of course in a loop I can use a counter.
The problem is that the Array is created with the static value of ""source" => "arrivals" for which there is only one value for the array and then the arrays of 'data'.
I would like an easy way to set up an array dynamically with a number of records but with the one header of ""source" => "arrivals" and multiple entries for "data' i.e. one element per record I fetch from my table
Thank you
You can do this with a foreach loop in php after you have retrieved your data.
// Get the data from your table source
$data = get_some_data();
$arrivals = [
'source' => 'arrivals',
'data' => []
];
foreach ($data as $city) {
$arrivals['data'][] = [
'flight' => $city['flight'],
'scheduled'=> $city['scheduled'],
'city' => $city['city'],
// etc.
];
}
Alternatively, if you would like to assign the city name as the array key in arrivals, you can replace the first line inside the foreach loop with $arrivals['data'][$city['city']] (or whatever array item holds the city value).
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
I am new to using multidimensional arrays with php, I have tried to stay away from them because they confused me, but now the time has come that I put them to good use. I have been trying to understand how they work and I am just not getting it.
What I am trying to do is populate results based on a string compare function, once I find some match to an 'item name', I would like the first slot to contain the 'item name', then I would like to increment the priority slot by 1.
So when when I'm all done populating my array, it is going to have a variety of different company names, each with their respective priority...
I am having trouble understanding how to declare and manipulate the following array:
$matches = array(
'name'=>array('somename'),
'priority'=>array($priority_level++)
);
So, in what you have, your variable $matches will point to a keyed array, the 'name' element of that array will be an indexed array with 1 entry 'somename', there will be a 'priority' entry with a value which is an indexed array with one entry = $priority_level.
I think, instead what you probably want is something like:
$matches[] = array(name => 'somename', $priority => $priority_level++);
That way, $matches is an indexed array, where each index holds a keyed array, so you could address them as:
$matches[0]['name'] and $matches[0]['priority'], which is more logical for most people.
Multi-dimensional arrays are easy. All they are is an array, where the elements are other arrays.
So, you could have 2 separate arrays:
$name = array('somename');
$priority = array(1);
Or you can have an array that has these 2 arrays as elements:
$matches = array(
'name' => array('somename'),
'priority' => array(1)
);
So, using $matches['name'] would be the same as using $name, they are both arrays, just stored differently.
echo $name[0]; //'somename';
echo $matches['name'][0]; //'somename';
So, to add another name to the $matches array, you can do this:
$matches['name'][] = 'Another Name';
$matches['priority'][] = 2;
print_r($matches); would output:
Array
(
[name] => Array
(
[0] => somename
[1] => Another Name
)
[priority] => Array
(
[0] => 1
[1] => 2
)
)
In this case, could this be also a solution with a single dimensional array?
$matches = array(
'company_1' => 0,
'company_2' => 0,
);
if (isset($matches['company_1'])) {
++$matches['company_1'];
} else {
$matches['company_1'] = 1;
}
It looks up whether the name is already in the list. If not, it sets an array_key for this value. If it finds an already existing value, it just raises the "priority".
In my opinion, an easier structure to work with would be something more like this one:
$matches = array(
array( 'name' => 'somename', 'priority' => $priority_level_for_this_match ),
array( 'name' => 'someothername', 'priority' => $priority_level_for_that_match )
)
To fill this array, start by making an empty one:
$matches = array();
Then, find all of your matches.
$match = array( 'name' => 'somename', 'priority' => $some_priority );
To add that array to your matches, just slap it on the end:
$matches[] = $match;
Once it's filled, you can easily iterate over it:
foreach($matches as $k => $v) {
// The value in this case is also an array, and can be indexed as such
echo( $v['name'] . ': ' . $v['priority'] . '<br>' );
}
You can also sort the matched arrays according to the priority:
function cmp($a, $b) {
if($a['priority'] == $b['priority'])
return 0;
return ($a['priority'] < $b['priority']) ? -1 : 1;
}
usort($matches, 'cmp');
(Sourced from this answer)
$matches['name'][0] --> 'somename'
$matches['priority'][0] ---> the incremented $priority_level value
Like David said in the comments on the question, it sounds like you're not using the right tool for the job. Try:
$priorities = array();
foreach($companies as $company) {
if (!isset($priorities[$company])) { $priorities[$company] = 0; }
$priorities[$company]++;
}
Then you can access the priorities by checking $priorities['SomeCompanyName'];.
I have a table that contains
column 1 = state column 2 = link
Alabama auburn.alabama.com
Alabama bham.alabama.com
Alabama dothan.alabama.com
I need to grab from my database table and put into an array that i can array_walk() through. they need to be accessed like this array.
$arraytable = array(
"auburn.alabama.com"=>"Alabama",
"bham.alabama.com"=>"Alabama",
"dothan.alabama.com"=>"Alabama",
);
I have tried everything but not sure how make this work using php to print the array like such. Any help is greatly appreciated.
Note Your question title is inconsistent with your example. In the title you ask for column 1 as the key, but your example uses column 2 as the key. I've used column 2 here...
It isn't clear what MySQL API you are using to fetch, but whichever it is, use the associative fetch method and create new array keys using the pattern $arraytable[$newkey] = $newvalue. This example would be in object-oriented MySQLi:
$arraytable = array();
while($row = $result->fetch_assoc()) {
// Create a new array key with the 'link' and assign the 'state'
$arraytable[$row['link']] = $row['state'];
}
You can use array_column for this, since PHP5.5 (http://php.net/array_column)
Description
array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
For PHP < 5.5:
https://github.com/ramsey/array_column/blob/master/src/array_column.php
To implement AcidReign's suggestion, here is the snippet:
Code: (Demo)
$resultset = [
['state' => 'Alabama', 'link' => 'auburn.alabama.com'],
['state' => 'Alabama', 'link' => 'bham.alabama.com'],
['state' => 'Alabama', 'link' => 'dothan.alabama.com']
];
var_export(array_column($resultset, 'state', 'link'));
// ^^^^-- use this column's data for keys
// ^^^^^-- use this column's data for values
Output:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)
However, array_column() won't directly work on a result set object, but a foreach() can immediately access the data set using array syntax without any fetching function calls.
Body-less foreach: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as ['link' => $link, 'state' => $result[$link]]);
var_export($result);
Or a foreach with a body: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as $row) {
$result[$row['link']] = $row['state'];
}
var_export($result);
All of the above snippets return:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)
Given this multidimensional array, I'm trying to retrieve the value of one of the child keys:
$movieCast = Array(
'1280741692' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
, '1280744592' => Array(
...
, 'userid' => 62
, 'country_id' => '00002'
...
)
)
How can I retrieve the value of country_id?
The top-level array key could be anything and the value of country_id will always be the same for a specific user. In this example, user #62's country_id will always be 00002.
You have to iterate through the outer array:
foreach ($outer as $inner) {
//do something with $inner["country_id"]
}
Another option is to build an array with the contry_ids (example uses PHP >=5.3 functionality, but that can be worked around easily in earlier versions):
array_map(function ($inner) { return $inner["country_id"]; }, $outer);
EDIT If the ids are all the same, even easier. Do:
$inner = reset($outer); //gives first element (and resets array pointer)
$id = $inner["country_id"];
a more general-purpose solution using php 5.3:
function pick($array,$column) {
return array_map(
function($record) use($column) {
return $record[$column];
},
$array
);
}
You need to use this:
array_column($movieCast, 'country_id')
The result will be:
array (
0 => '00002',
1 => '00002',
)