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).
Related
I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.
$arrImages[] =
[
'img_sm'=>'image1.jpg',
'tag_GlassDoor'=>0,
'tag_GlassWall'=>1,
];
$arrImages[] =
[
'img_sm'=>'image2.jpg',
'tag_GlassDoor'=>1,
'tag_GlassWall'=>1,
];
Filtering is the answer, it can be used to filter one dimensional Arrays and multidimensional arrays.
the general implementation would be something like this:
$arr = array(
array(
'image' => "data",
'hasObject' => 1
),
array(
'image' => "data",
'hasObject' => 0
),
);
$finteredArray = array_filter($arr, function ($r) {
return (bool) $r['hasObject'];
});
print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )
I'm looking for a smart way to find out if my array of objects within an object has multiple name values or not to do a validation since it's only allowed to have one array name per inner array:
$elements = [];
$elements[18][20] = [
[
'name' => 'Color',
'value' => 'Red'
],
[
'name' => 'Color',
'value' => 'Green'
],
[
'name' => 'Size',
'value' => 'S'
]
];
$elements[18][21] = [
[
'name' => 'Size',
'value' => 'S'
],
[
'name' => 'Length',
'value' => '20'
],
];
error_log( print_r( $elements, true ) );
So the object 20 for example is invalid because it has 2 colors with the same value. At the end I was hoping to get a result array containing 1 duplicate name. This way I can output them like: "You have at least one duplicate name: Color".
My first idea was to loop over the array and do a second loop. This way it was possible to receive the inner arrays containing the stuff. Now I was able to add every name to another array. After this I was able to use count() and array_intersect() to receive a value of x which showed me if there are duplicates or not.
Now I had a count, but not the actual value to display. Before I use a semi-good solution, I was hoping to get any ideas here how I can make it better!
This loop will generate your expected output:
foreach($elements[18] as $index => $element){
//Get all the elements' names
$column_key = array_column($element, 'name');
//Get the count of all keys in the array
$counted_values = array_count_values($column_key);
//Check if count is > 1
$filtered_array = array_filter($counted_values, fn($i) => $i > 1);
//If the filter is not empty, show the error
if(!empty($filtered_array)){
//get the key name
$repeated_key = array_key_first($filtered_array);
echo "You have at least one duplicate name: {$repeated_key} at index {$index}";
break;
}
}
It relies in the array_count_values function.
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.
{
"word": ["w1", "w2"],
"meaning": ["m1", "m2"],
"parts_of_speech": ["p1", "p2"],
}
This is the Data i have in Model which is now assigned to $data variable
In above $data each word index has corresponding Meaning in meaning array, and each word index has corresponding parts_of_speech in parts_of_speech array index. In this way always length of word,meaning,parts_of_speech arrays remain same
I have tried the following methods to insert into table
$this->db->insert('table_words', $data);
$this->db->insert_batch("table_words",$data);
but it happened errors
CodeIginter accepts array for insert in which key should be 'column name' and value value should be record which we want to insert. As i can understand you have to insert multiple rows, So you have to use batch insert.
Try below code :
$data = array(
array(
'word' => 'w1' ,
'meaning' => 'm1' ,
'parts_of_speech' => 'p1'
),
array(
'word' => 'w2' ,
'meaning' => 'm2' ,
'parts_of_speech' => 'p2'
)
);
$this->db->insert_batch('mytable', $data);
Your json should be like this
[{"word":"w1","meaning":"m1","parts_of_speech":"p1"},{"word":"w2","meaning":"m2","parts_of_speech":"p2"}]
`Say I have an associative array like so:
$array = array(
'names' => array('amy','john', 'peter'),
'places' => array('milan', 'venice', 'amsterdam'),
'uncategorized' => array('desk', 'plane', 'silly'),
'jobs' => array('singer', 'clerk', 'broker')
);
Now suppose I want to save uncategorized into a new array and remove it from $array, I can do:
$uncategorized = $array['uncategorized'];
unset($array['uncategorized']);
My question is, is there any single function that does it kind of like how array_pop returns the last value and shortens the array by that element?