States foreach loop not listing all states - php

I have a drop down menu on my site where I want all US states listed. I have an array of states but I can't seem to get ALL of them to load into my <option> tag. Below is the first 15 states as an array and my <select> code. Eventually the drop down will link to separate pages for each state with an image of that state (that is why I have an "img" within each state array). The only states I get to load in the drop down are: Alaska, Arkansas, Colorado, Delaware, Florida, Hawaii, and Illinois.
<?php
$states = array();
$states['AL'] = array (
"name" => "Alabama",
"img" => "http://getwidgetsfree.com/images/state_png/al.png"
);
$states['AK'] = array (
"name" => "Alaska",
"img" => "http://getwidgetsfree.com/images/state_png/ak.png"
);
$states['AZ'] = array (
"name" => "Arizona",
"img" => "http://getwidgetsfree.com/images/state_png/az.png"
);
$states['AR'] = array (
"name" => "Arkansas",
"img" => "http://getwidgetsfree.com/images/state_png/ar.png"
);
$states['CA'] = array (
"name" => "California",
"img" => "http://getwidgetsfree.com/images/state_png/ca.png"
);
$states['CO'] = array (
"name" => "Colorado",
"img" => "http://getwidgetsfree.com/images/state_png/co.png"
);
$states['CT'] = array (
"name" => "Connecticut",
"img" => "http://getwidgetsfree.com/images/state_png/ct.png"
);
$states['DE'] = array (
"name" => "Delaware",
"img" => "http://getwidgetsfree.com/images/state_png/de.png"
);
$states['DC'] = array (
"name" => "District of Columbia",
"img" => "http://pharmacoding.com/dendreon/provenge/images/dc.png"
);
$states['FL'] = array (
"name" => "Florida",
"img" => "http://getwidgetsfree.com/images/state_png/fl.png"
);
$states['GA'] = array (
"name" => "Georgia",
"img" => "http://getwidgetsfree.com/images/state_png/ga.png"
);
$states['HI'] = array (
"name" => "Hawaii",
"img" => "http://getwidgetsfree.com/images/state_png/hi.png"
);
$states['ID'] = array (
"name" => "Idaho",
"img" => "http://getwidgetsfree.com/images/state_png/id.png"
);
$states['IL'] = array (
"name" => "Illinois",
"img" => "http://getwidgetsfree.com/images/state_png/il.png"
);
$states['IN'] = array (
"name" => "Indiana",
"img" => "http://getwidgetsfree.com/images/state_png/in.png"
);
?>
<select>
<?php
foreach($states as $state) {
echo "<option value='state.php?id=" . $state["id"] . ">" . $state["name"] . "</option>";
};
?>
</select>

You are missing a closing ``' quote, next to the option tag’s closing bracket right after $state["id"].
<?php
foreach($states as $state) {
echo "<option value='state.php?id=" . $state["id"] . "'>" . $state["name"] . "</option>";
};
?>

To answer the most immediate question, you are missing a closing quote when you set <option>. Then you are setting $state["id"] when that key doesn’t exist in the structure you have. You should be using the actual key in that array.
So with that in mind, here is my re-factored version of the code. Note you can use string substitution with double quotes (") so no need for concatenation. Which makes this easier to read and debug as well.
echo '<select>';
foreach($states as $state_key => $state_value) {
echo "<option value='state.php?id=$state_key'>"
. $state_value["name"]
. "</option>"
;
};
echo '</select>';
That said, you can simplify your code by using an array like this:
$states = array();
$states['al'] = array('name' => 'Alabama');
$states['ak'] = array('name' => 'Alaska');
$states['az'] = array('name' => 'Arizona');
$states['ar'] = array('name' => 'Arkansas');
$states['ca'] = array('name' => 'California');
$states['co'] = array('name' => 'Colorado');
$states['ct'] = array('name' => 'Connecticut');
$states['de'] = array('name' => 'Delaware');
$states['de'] = array('name' => 'Delaware');
$states['dc'] = array('name' => 'District of Columbia');
$states['fl'] = array('name' => 'Florida');
$states['ga'] = array('name' => 'Georgia');
$states['hi'] = array('name' => 'Hawaii');
$states['id'] = array('name' => 'Idaho');
$states['il'] = array('name' => 'Illinois');
$states['in'] = array('name' => 'Indiana');
echo '<select>';
foreach($states as $state_key => $state_value) {
$states[$state_key] = array_merge($states[$state_key], array('img' => "http://getwidgetsfree.com/images/state_png/$state_key.png"));
$state_key_uc = strtoupper($state_key);
echo "<option value='state.php?id=$state_key_uc'>"
. $state_value['name']
. "</option>"
;
};
echo '</select>';
The goal is you are starting out with a basic array that has the lowercase state code for the array key. Then set the name as you did before. But when you do the foreach loop, then you just set the img value & merge that using array_merge into the existing array.

Related

how to add json serilize data into the database using php

This is my array and i want to convert this as json and added to the database
Array(
[0] => Array
(
[id] => e4da3b7fbbce2345d7772b0674a318d5
[channel] => Array
(
[0] => 1
[1] => 2
)
)
)
I want to store data like this where id remain same and channel will add to the next json bracket with same id
[{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":1},{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":2}]
Code
$var1 = array([
'id' => $hash_user,
'channel' => $channel
]);
// print_r($var1);
foreach($var1 as $id){
$encode_data = $id['id'] . $id['channel'][0]. $id['id'] . $id['channel'][1];
$see = json_encode($encode_data);
}
print_r($see);
print_r($encode_data);
//
die;
$info['user_hash'] = $encode_data;
You should be clear in your post. But given the information, I assume you need to change the array you have to that JSON.
What you have:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]]];
$json = json_encode($databaseArray);
What you want:
$databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => 1]];
$json = json_encode($databaseArray);
What you need to change:
$databaseArray = [
[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]],
[ "id" => "1235437fbbce2345d7772b0674a32342", "channel" => [1,2]]
];
$databaseMergedArray = [];
// You need to set the channel to a value instead of array.
foreach($databaseArray as $key => $item) {
foreach($databaseArray[$key]["channel"] as $channel) {
$item["channel"] = $channel;
$databaseMergedArray[] = $item;
}
}
$json = json_encode($databaseMergedArray);
echo ($json);

How do I compare these two Arrays for sameness?

I have an array consisting of seat number in the following format
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
?>
And also the retrieved data of reserved seats by users which comes in this format
<?php
$seat = array();
$sql = $db->query("SELECT booked_seat FROM mybooking where bus_id = '{$l}'");
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r){
$seat[] = $r['booked_seat'];
}
print_r($seat)
// Array ( [0] => A1 [1] => D2 )
?>
All I am trying to achieve is to disable the selected seats in a HTML select like I tried doing here
<?php
$keys = array_keys($seatnumbers);
$values = array_values($seatnumbers);
$skeys = array_keys($seat);
$val = array_values($seat);
for($i = 0; $i < 14; $i++ )
{
if($keys[$i] == $val[$i]){
echo "<option disabled>". $keys[$i]. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $keys[$i]."-". $val[$i]. "(Available)</option>";
}
}
?>
But only the first option showed booked. How do compare for two arrays to disabled the reserved seats.
Here is the result of what I tried
Using prepared statements and also using PDO::FETCH_COLUMN to save having to process the result set from the SQL further. The code has comments to show how this is done.
You will have to change the output, but it matches what you have enough to modify it...
$query = "SELECT booked_seat FROM mybooking where bus_id = :busID";
$sql = $db->prepare($query);
$sql->execute(["busID" => $l]);
// Fetch an array with just the values of booked_seat
$seat=$sql->fetchAll(PDO::FETCH_COLUMN, 0);
// Flip array so the seat name becomes the key
$seat = array_flip($seat);
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
foreach ( $seatnumbers as $seatName => $number ) {
echo $seatName;
// If the key is set in the seat array, then it is booked
if ( isset($seat[$seatName]) ){
echo " Seat booked".PHP_EOL;
}
else {
echo " Seat not booked".PHP_EOL;
}
}
This is a typical task for using foreach
<html>
<head></head>
<body>
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
$seat = array(
"0" => "A1","1" => "D2",
"2" => "E1","3" => "E2","4" => "E3"
);
echo "<select>";
foreach ($seatnumbers as $ikey=>$ivalue)
{
if(in_array($ikey,$seat)){
echo "<option disabled>". $ikey. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $ikey."-". $val[$i]. "(Available)</option>";
}
}
echo "</select>";
?>
</body>
</html>

Regroup multidimensional array to reverse presentation of many-to-many relationship

I need to perform iterated explosions on values in one column of my two dimensional array, then re-group the data to flip the relational presentation from "tag name -> video id" to "video id -> tag name".
Here is my input array:
$allTags = [
[
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
[
"name" => "TAG-THREE",
"video" => "64111",
]
];
I want to isolate unique video ids and consolidate all tag names (as comma-separayed values) that relate to each video id.
Expected output:
$allTagsResult = [
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64070",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64076",
],
[
"name" => "TAG-ONE,TAG-TWO",
"video" => "64110",
],
[
"name" => "TAG-ONE,TAG-TWO,TAG-THREE",
"video" => "64111",
],
];
Somehow I did it by checking the value using nested loops but I wish to know if you guys can suggest any shortest method to get the expected output.
If you want to completely remove foreach() loops, then using array_map(), array_walk_recursive(), array_fill_keys() etc. can do the job. Although I think that a more straightforward answer using foreach() would probably be faster, but anyway...
$out1 = array_map(function ($data) {
return array_fill_keys(explode(",", $data['video']), $data['name']); },
$allTags);
$out2 = [];
array_walk_recursive( $out1, function ( $data, $key ) use (&$out2) {
if ( isset($out2[$key])) {
$out2[$key]['name'] .= ",".$data;
}
else {
$out2[$key] = [ 'name' => $data, 'video' => $key ];
}
} );
print_r($out2);
will give...
Array
(
[64070] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64070
)
[64076] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64076
)
[64110] => Array
(
[name] => TAG-ONE,TAG-TWO
[video] => 64110
)
[64111] => Array
(
[name] => TAG-ONE,TAG-TWO,TAG-THREE
[video] => 64111
)
)
if you want to remove the keys, then
print_r(array_values($out2));
The code could be compressed by piling all of the code onto single lines, but readability is more useful sometimes.
Another method if you don't like looping:
$video_ids = array_flip(array_unique(explode(",",implode(",",array_column($allTags,'video')))));
$result = array_map(function($id){
return ['name' => '','video' => $id];
},array_flip($video_ids));
array_walk($allTags,function($tag_data) use (&$result,&$video_ids){
$ids = explode(",",$tag_data['video']);
foreach($ids as $id) $result[$video_ids[$id]]['name'] = empty($result[$video_ids[$id]]['name']) ? $tag_data['name'] : $result[$video_ids[$id]]['name'] . "," . $tag_data['name'];
});
Demo: https://3v4l.org/vlIks
Below is one way of doing it.
$allTags = [
'0' => [
"name" => "TAG-ONE",
"video" => "64070,64076,64110,64111",
],
'1' => [
"name" => "TAG-TWO",
"video" => "64070,64076,64110,64111",
],
'2' => [
"name" => "TAG-THREE",
"video" => "64111",
]
];
$allTagsResult = array();
$format = array();
foreach( $allTags as $a ) {
$name = $a['name'];
$videos = explode(',', $a['video']);
foreach( $videos as $v ) {
if( !isset( $format[$v]) ) {
$format[$v] = array();
}
$format[$v][] = $name;
}
}
foreach( $format as $video => $names) {
$allTagsResult[] = array('name' => implode(',', $names), 'video' => $video);
}
echo '<pre>';
print_r($allTagsResult);
die;
You can check Demo
I am typically in favor of functional style coding, but for this task I feel it only serves to make the script harder to read and maintain.
Use nested loops and explode the video strings, then group by those video ids and concatenate name strings within each group. When finished iterating, re-index the array.
Code: (Demo)
$result = [];
foreach ($allTags as $tags) {
foreach (explode(',', $tags['video']) as $id) {
if (!isset($result[$id])) {
$result[$id] = ['video' => $id, 'name' => $tags['name']];
} else {
$result[$id]['name'] .= ",{$tags['name']}";
}
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'video' => '64070',
'name' => 'TAG-ONE,TAG-TWO',
),
1 =>
array (
'video' => '64076',
'name' => 'TAG-ONE,TAG-TWO',
),
2 =>
array (
'video' => '64110',
'name' => 'TAG-ONE,TAG-TWO',
),
3 =>
array (
'video' => '64111',
'name' => 'TAG-ONE,TAG-TWO,TAG-THREE',
),
)

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

Echo part of an array based on key => value match

I have an array structured like so:
<?php
$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
?>
What I need to do is find the service_type_* part of the array, then echo all of the key value pairs until it reaches the next service_type_* where the loop then breaks.
Now this would be easy enough to do with a static data set but the array can change in size and each form can change depending on different variables, which is why the service_type_* key value entry is there.
Any ideas would be appreciated.
EDIT for clarification:
I basically need so that if I need, for example, the form data for web hosting, it would find the service_type_web key and return the following:
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
...And leaves out:
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
SECOND EDIT:
OK, I'm nearly there. I've come up with the following:
$delimiter = 0;
$array_counter = 0;
foreach($orderdata as $orderkey => $ordervalue) {
if($orderkey == "service_type_web") {
$new_array = array_slice($orderdata, $array_counter);
$array_counter ++;
$delimiter = 1;
} elseif(preg_match('/service_type_[a-z\_]+/', $orderkey)) {
if($delimiter == 1) {
echo $orderkey . " => " . $ordervalue . "<br />\n";
break;
}
} else {
$array_counter ++;
}
}
However the break in the if statement isn't working, even though when I get it to echo the key/value pair for the current array pointer, it echos
"service_type_ssl" => "on"
Anyone know why? Kinda stumped.
You can check "key" before you loop into it, by using array_key_exists
$orderdata = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
if (array_key_exists('service_type_web', $orderdata )) {
echo "array found";
}
A possible solution is. This answer may guide you in right direction but still you need to do some minor changes.
$input = array(
"service_type_web" => "on",
"custid" => "A12345",
"domain_web" => "foo.com",
"cust_email_web" => "foo#bar.com",
"plantype" => "dynamic",
"platform" => "unix",
"service_type_ssl" => "on",
"custid" => "A23456",
"common_name" => "foo.bar.com",
"cust_email_ssl" => "bar#foo.com"
);
function preg_grep_keys($pattern, $input, $flags = 0) {
return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
$a = preg_grep_keys("/service_type_[a-z]*/", $input);
print_r($a);
expected output will be
Array ( [service_type_web] => on [service_type_ssl] => on )
taken from http://php.net/manual/en/function.preg-grep.php

Categories