How to access specific values for specific keys in php array - php

I want to show specific values according to specific keys in a array.
there are some keys which are fetched from database then i want to show its meaningful values like:
array('12_01'=>'12:00 - 01:00','01_02'=>'01:00 - 02:00');
here is code:
<?php echo implode(',',$selected_hours); ?>
And here is Array:
$hourshow = array('12_01'=>'12:00 - 01:00',
'01_02'=>'01:00 - 02:00',
'02_03'=>'02:00 - 01:03',
'03_04'=>'03:00 - 04:00',
'04_05'=>'04:00 - 05:00',
'05_06'=>'05:00 - 06:00',
'06_07'=>'06:00 - 07:00',
'07_08'=>'07:00 - 08:00',
'07_09'=>'08:00 - 09:00',
'09_10'=>'09:00 - 10:00',
'10_11'=>'10:00 - 11:00',
'11_12'=>'11:00 - 12:00',
'12_13'=>'12:00 - 13:00',
'13_14'=>'13:00 - 14:00',
'14_15'=>'14:00 - 15:00',
'15_16'=>'15:00 - 16:00',
'16_17'=>'16:00 - 17:00',
'17_18'=>'17:00 - 18:00',
'18_19'=>'18:00 - 19:00',
'19_20'=>'19:00 - 20:00',
'20_21'=>'20:00 - 21:00',
'21_22'=>'21:00 - 22:00',
'22_23'=>'22:00 - 23:00',
'23_24'=>'23:00 - 24:00',
);

$keys = array('12_01','01_02','02_03','03_04','04_05','05_06','06_07','07_08','08_09','09_10','10_11','11_12');
$result = array();
foreach($keys as $value){
$val = explode('_',$value);
$result[$value] = $val[0].':00 - '.$val[1].':00';
}
echo '<pre>';print_r($result);exit;
You can try with this code. You will getting result in result array.

Use ksort():
$hourshow = array(...);
ksort($hourshow);
// $hourshow is now sorted according to key.

Dont know if I get your question correctly, but this should be what you are looking for
array_intersect_key($hourshow, array_flip($yourWantedHoursArray));

#Ashish Vyas Simply do it like below
<?php
$youKeysFetchedFromDb = array("12_01", "01_02"); //suppose
foreach($youKeysFetchedFromDb as $value){
echo $hourshow[$value];
}

Related

Best practice for looping through a nested array php

I am writing in PHP.
What I am trying to do is something like a configurable product in Magento2 or variable product in Woocommerce. I am asking the user to enter attributes to the product, like color, size, etc'.
Think of each attribute as a attribute category which contains attributes inside it, e.g 'color' will have attributes like 'red', 'green', 'blue' and so on. Size will have attributes like 'large', 'small', 'medium' and so on.
Now, I need to make a loop which takes all sizes, colors and other chosen attributes and returns all the possible configurations. At the same time the amount of attributes to loop through isn't predefined since the user can add or remove attributes.
For example if I have this:
Color - - - - - - - - Size - - - - - - - - Shape
Red - - - - - - - - - Large - - - - - - - Square
Green - - - - - - - - Medium - - - - - - - Rounded
Blue - - - - - - - - Small - - - - - - - -
So I will have to have every color with every size and shape:
Red - Large - Square
Red - Large - Rounded
Red - Medium - Square
Red - Medium - Rounded
Red - Small - Square
Red - Small - Rounded
And the same with the other attributes.
What is the best practice to achive it?
You will need recursion for this.
function getCombinations($attributes){
$combinations = [];
buildCombinationChain($attributes,0,[],$combinations);
// encode combinations to desired string format
$result = [];
foreach ($combinations as $combination) {
$result[] = implode(' - ', $combination);
}
return $result;
}
function buildCombinationChain($attributes,$index,$chain,&$output){
if($index>=count($attributes)){
// we have reached the last attribute, stop recursion and push the current chain to the output array
$output[] = $chain;
return;
}
foreach ($attributes[$index] as $attribute) {
$new_chain = $chain; // create a copy of the current chain
$new_chain[] = $attribute; // and add the current attribute to it
buildCombinationChain($attributes,$index+1,$new_chain,$output); // continue recursively on the next attribute group
}
}
$attributes = [
['Red', 'Green', 'Blue'],
['Large', 'Medium', 'Small'],
['Square', 'Rounded']
];
echo json_encode(getCombinations($attributes));

Laravel Blade is displaying incorrect values for select dropdown

I'm using Laravel 5.4 and I'm creating a form in Blade and one of the <select> is of all the months.
#php (
$months = [
'1'=>'01 - January',
'2'=>'02 - February',
'3'=>'03 - March',
'4'=>'04 - April',
'5'=>'05 - May',
'6'=>'06 - June',
'7'=>'07 - July',
'8'=>'08 - August',
'9'=>'09 - September',
'10'=>'10 - October',
'11'=>'11 - November',
'12'=>'12 - December',
]
)
{{Form::select('card_month', array_merge(['' => 'Select Month'], $months),null,['id' => 'exp_month'])}}
When I use Inspect Element to look at the dropdown I see this
The keys in the $months array don't match the values in Inspect Element.
The values start off at 0 instead of 1.
BUT If I add a space in front of the keys, then the numbers display correctly under Inspect Element.
' 1'=>'01 - January',
' 2'=>'02 - February',
' 3'=>'03 - March',
' 4'=>'04 - April',
' 5'=>'05 - May',
' 6'=>'06 - June',
' 7'=>'07 - July',
' 8'=>'08 - August',
' 9'=>'09 - September',
' 10'=>'10 - October',
' 11'=>'11 - November',
' 12'=>'12 - December',
Why is this happening and how do I fix it?
This is not Laravel fault, this is how array_merge function behaves:
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Sorting 2 fields ASC in array with usort (PHP)

i have a textfile with this content (id;date;user):
8559;2014-06-13;Carlos
8584;2014-06-23;1A Auto
8398;2014-06-02;LRDream
7738;2014-05-19;Felicitia Motors
8475;2014-06-06;Motori
8331;2014-06-30;Otto Burner
8521;2014-06-24;Mirage
3699;2014-06-30;LR DMJ
8050;2014-05-19;1A Auto
7428;2014-05-20;Carlos
Goal is to output this data sorted by 1) month and 2) username.
<?
$data = file("data.csv");
foreach ($data as $value)
{
$bla=explode(";",$value);
$new[$bla[0]]['date']=substr($bla[1],0,-3);
$new[$bla[0]]['user']=$bla[2];
}
function comp($a, $b)
{ if ($a['date'] == $b['date']) { return $a['user'] - $b['user']; }
return strcmp($a['date'], $b['date']);
}
usort($new, 'comp');
foreach ($new as $value)
{
echo $value['date']." - ".$value['user']."<br>";
}
?>
This sorts the months correctly but the users are not really sorted:
2014-05 - Carlos
2014-05 - Felicitia Motors
2014-05 - 1A Auto <---
2014-06 - LR DMJ
2014-06 - Mirage
2014-06 - Motori
2014-06 - LRDream <---
2014-06 - Carlos <---
2014-06 - Otto Burner
2014-06 - 1A Auto <---
What wrong with the code?
Thanks!
NBG
That's because you are not comparing the usernames -- you are subtracting them numerically, which gives totally inappropriate results (see string conversion to numbers).
Replace return $a['user'] - $b['user'] with return strcmp($a['user'], $b['user']) to get the expected result.
Shameless self-promotion: You could also consider using the handy sorting technique I give here to get the correct result with much more appealing code:
usort($new, make_comparer('date', 'user'));

awkward duplication in 2d array php

I merged two arrays together that both contained a string(url) and int(score). the following is a sample of the outome. Whenever a string is duplicated, i need to remove that string and its corresponding int. For example, on the 4th line (www.thebeatles.com/ - 30) should be removed. The 5th and 6th lines should also be removed as they appear already with a different score.
http://www.thebeatles.com/ - 55
http://en.wikipedia.org/wiki/The_Beatles - 49
http://www.beatlesstory.com/ - 45
http://www.thebeatles.com/ - 30
http://en.wikipedia.org/wiki/The_Beatles - 28
http://www.beatlesstory.com/ - 26
http://www.beatlesagain.com/ - 24
http://www.thebeatlesrockband.com/ - 23
http://www.last.fm/music/The+Beatles - 22
http://itunes.apple.com/us/artist/the-beatles/id136975 - 20
http://www.youtube.com/watch?v=U6tV11acSRk - 18
http://blekko.com/ws/http://www.thebeatles.com/+/seo - 17
http://www.adriandenning.co.uk/beatles.html - 16
http://www.npr.org/artists/15229570/the-beatles - 15
http://mp3.com/artist/The%2BBeatles - 14
http://www.beatles.com/ - 13
http://www.youtube.com/watch?v=TU7JjJJZi1Q - 12
http://www.guardian.co.uk/music/thebeatles - 11
http://www.cirquedusoleil.com/en/shows/love/default.aspx - 9
http://www.recordingthebeatles.com/ - 7
http://www.beatlesbible.com/ - 5
I'm new to PHP and my best efforts to get array_unique() to work have failed. Really appreciate some help guys!
Here is a function that merges two arrays and discards any duplications, hopes it helps:
function merge_links($arr_l, $arr_r) {
$new_links = array();
$links = array_merge($arr_l, $arr_r); //the big list with every links
foreach($links as $link) {
$found = false; //did we found a duplicate?
//check if we already have it
foreach($new_links as $new_link) {
if($new_link['url'] == $link['url']) {
//duplicate
$found = true;
break;
}
}
//not found, so insert it
if(!$found) {
$new_links[] = $link;
}
}
return $new_links;
}
$arr1[0]['url'] = 'http://test.nl';
$arr1[0]['score'] = 30;
$arr1[1]['url'] = 'http://www.google.nl';
$arr1[1]['score'] = 30;
$arr2[0]['url'] = 'http://www.tres.nl';
$arr2[0]['score'] = 30;
$arr2[1]['url'] = 'http://test.nl';
$arr2[1]['score'] = 30;
print_r(merge_links($arr1, $arr2));
You can make link as key of the array which contains link and score. Corresponding to key there will always be one value. But the one which is added in the last will be there in your final array.
Well, even technically, those strings are not unique. i.e. They are completely different.
http://www.thebeatles.com/ - 55
http://www.thebeatles.com/ - 30
So, array_unique() will not give you the required output. One way of solving this issue is by defining a separate array and storing the URI and the number separately. A manageable form would be this.
array(
array("http://www.thebeatles.com", 55),
array("http://www.thebeatles.com", 30)
);

To select a specific column from a table using php postgres

I have table of 5000+ rows and 8+ columns like,
Station Lat Long Date Rainfall Temp Humidity Windspeed
Abcd - - 09/09/1996 - - - -
Abcd - - 10/09/1996 - - - -
Abcd - - 11/09/1996 - - - -
Abcd - - 12/09/1996 - - - -
Efgh - - 09/09/1996 - - - -
Efgh - - 10/09/1996 - - - -
Efgh - - 11/09/1996 - - - -
Efgh - - 12/09/1996 - - - -
I am developing a web application, in that user will select a column like rainfall/temp/humidity and for a particular date.
Can anyone guide me how to query for this in php-postgres. (database:postgres, table:weatherdata, user:user, password:password)
Thanks in advance.
You can use some code like this:
public function getData ($date, $columnsToShow = null) {
/* You could check the parameters here:
* $date is string and not empty
* $columnsToShow is an array or null.
*/
if (isset ($columnsToShow))
$columnsToShow = implode (',', $columnsToShow);
else $columnsToShow = "*";
$query = "select {$columnsToShow}
from table
where date = '{$date}'";
$result = array();
$conex = pg_connect ("host=yourHost user=yourUser password=yourUser dbname=yourDatabase");
if (is_resource ($conex)) {
$rows = pg_query ($conex, $query);
if ($rows) {
while ($data = pg_fetch_array ($rows, null, 'PGSQL_ASSOC'))
$result[] = $data;
}
}
return (empty ($result) ? null : $result);
}
Now you can invoke, for example, like this:
getData ('2012-03-21', array ('Station', 'Rainfall'));
I hope you serve.

Categories