Jump to content

Search the Community

Showing results for tags 'arrays'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. How do you selectively BOLD output array elements from three arrays? My code has only one output line. I am creating a madlib php program and I want my nouns to be in bold, my verbs to be italicized, and my adjectives to be underlined. Where would I implement this? Thanks. Here is my code: $counter=0; $nounCounter=0; $verbCounter=0; $adjCounter=0; $newSentArray = $sentArray; // copy $sentArray while ( $counter < count($sentArray)) // loop over words in array { if($sentArray[$counter] == "NOUN" or $sentArray[$counter] == "NOUN." or $sentArray[$counter] == "NOUN!") { // replace current word with noun $newSentArray[$counter] = $nounArray[$nounCounter]; $nounCounter++; // increment noun, so next noun in used for replacement } elseif($sentArray[$counter] == "VERB" or $sentArray[$counter] == "VERB." or $sentArray[$counter] == "VERB!") { // replace current word with verb $newSentArray[$counter] = $verbArray[$verbCounter]; $verbCounter++; // increment verb, so next verb in used for replacement } elseif($sentArray[$counter] == "ADJECTIVE" or $sentArray[$counter] == "ADJECTIVE." or $sentArray[$counter] == "ADJECTIVE!") { // replace current word with adjective $newSentArray[$counter] = $adjArray[$adjCounter]; $adjCounter++; // increment adjective, so next adjective in used for replacement } $counter++; } // implode words array into a string echo implode(' ', $newSentArray);
  2. Can anyone help me? I am a student and I have been working on a PHP project for over two weeks with no luck on one piece of code. The project is a small "Madlib" project, but I'm only having trouble with one piece of code. Any takers? All I'm trying to do is get a sentence like "I bought a NOUN and NOUN." to be replaced with "I bought a cat and a dog." The problem is, I get this: "I bought a cat and a cat." I have tried all the loops I can try. Yes, I'm a newbie, but I'm desperate and can't figure this out. I have my html and php code, also the URL to the website. Any help would greatly be appreciated. Thanks. I have attached my html and my php file to this posting. project1.htmlproject1.php I have posted the small piece of code I am having a problem with down below: $counter=0; $nounCounter=0; while ( $counter < $sentLength and $nounCounter < $nounLength) { if($sentArray[$counter]=="NOUN") { $newSent = str_replace($sentArray[$counter], $nounArray[$nounCounter], $initialSent); } $counter++; echo $newSent . '<br .>';
  3. I have a working example below of a single file input upload via php and now I'd like to upload multiple files either by iterating through each input type="file". I've read that the multiple attribute on the input tag is not supported below IE10 so I think the best way would be to have several input type=files in order to loop through them any help is appreciated <input type="file" name="FilesUpload1" class="filesUpload" /> <input type="file" name="FilesUpload2" class="filesUpload" /> <input type="file" name="FilesUpload3" class="filesUpload" /> <?php //Сheck that we have a file if((!empty($_FILES["FilesUpload1"])) && ($_FILES['FilesUpload1']['error'] == 0)) { //Check if the file is JPEG image and it's size is less than 350Kb $filename = basename($_FILES['FilesUpload1']['name']); $ext = substr($filename, strrpos($filename, '.') + 1); //check file extension if ((($ext == "gif") || ($ext == "jpeg") || ($ext == "jpg") || ($ext == "png") || ($ext == "doc") || ($ext == "docx") || ($ext == "rtf") || ($ext == "txt") || ($ext == "pdf")) //check file mime && (($_FILES["FilesUpload1"]["type"] == "image/gif") || ($_FILES["FilesUpload1"]["type"] == "image/jpeg") || ($_FILES["FilesUpload1"]["type"] == "image/jpg") || ($_FILES["FilesUpload1"]["type"] == "image/pjpeg") || ($_FILES["FilesUpload1"]["type"] == "image/x-png") || ($_FILES["FilesUpload1"]["type"] == "image/png") || ($_FILES["FilesUpload1"]["type"] == "application/msword") || ($_FILES["FilesUpload1"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") || ($_FILES["FilesUpload1"]["type"] == "application/rtf") || ($_FILES["FilesUpload1"]["type"] == "text/plain") || ($_FILES["FilesUpload1"]["type"] == "application/pdf")) //check file size is less than 1048576 bytes [1 MB] && (($_FILES["FilesUpload1"]["size"] < 1048576))) { //Determine the path to which we want to save this file $newname = dirname(__FILE__).'/../entries/'.$_POST["CompanyName"].'-'.$filename; //Check if the file with the same name is already exists on the server if (!file_exists($newname)) { //Attempt to move the uploaded file to it's new place if ((move_uploaded_file($_FILES['FilesUpload1']['tmp_name'],$newname))) { echo "It's done! Your file has been saved."; } else { echo "Error: A problem occurred during file upload!"; } } else { echo "Error: File ".$_FILES["FilesUpload1"]["name"]." already exists"; } } else { echo "Error: Only .gif, .jpeg, .jpg, .png, .doc, .docx, .rtf, .txt, .pdf files under 1 MB are accepted for upload."; } } else { echo "Error: No file uploaded"; } ?>
  4. I want to list results that belong to a certain category. However, I have multiple categories and some results can belong to more than one cateogry. I want to a query that will show all the results from several categories, the number of categories will be aribitrary though. So I will have the categories contained within an array e.g. $cat_ids = array(12,26,32) And I want the query to be $sql = "SELECT * FROM `categories` WHERE `cat_id`=12 OR `cat_id`=26 OR `cat_id`=32"; Of course sometimes there may only be 1 category, and sometimes there could be 5. So how do you execute the array in the query? Or do I have to run a foreach loop? $sql = "SELECT * FROM `categories` WHERE" $i = 0; foreach ($cat_ids AS $cat_id){ if($i!=0) $sql = "OR " $sql = "`cat_id`=$cat_id" $i++ }
  5. Please ignore the fact i have a form etc in my class and it submits to the class, what i am stuck on is finding the value from my associative array with the key that passed in the $_POST request. I have looked in the php manual and looked at other fixes people have posted online but something is not right. Easy fix for a seasoned developer i am sure, please help if you have a min. <?php class World { public $world_countries = array( "GB" => "United Kingdom", "US" => "United States", "AF" => "Afghanistan", "AL" => "Albania", "DZ" => "Algeria", "AS" => "American Samoa", "AD" => "Andorra", "AO" => "Angola", "AI" => "Anguilla", "AQ" => "Antarctica", "AG" => "Antigua And Barbuda", "AR" => "Argentina", "AM" => "Armenia", "AW" => "Aruba", "AU" => "Australia", "AT" => "Austria", "AZ" => "Azerbaijan", "BS" => "Bahamas", "BH" => "Bahrain", "BD" => "Bangladesh", "BB" => "Barbados", "BY" => "Belarus", "BE" => "Belgium", "BZ" => "Belize", "BJ" => "Benin", "BM" => "Bermuda", "BT" => "Bhutan", "BO" => "Bolivia", "BA" => "Bosnia And Herzegowina", "BW" => "Botswana", "BV" => "Bouvet Island", "BR" => "Brazil", "IO" => "British Indian Ocean Territory", "BN" => "Brunei Darussalam", "BG" => "Bulgaria", "BF" => "Burkina Faso", "BI" => "Burundi", "KH" => "Cambodia", "CM" => "Cameroon", "CA" => "Canada", "CV" => "Cape Verde", "KY" => "Cayman Islands", "CF" => "Central African Republic", "TD" => "Chad", "CL" => "Chile", "CN" => "China", "CX" => "Christmas Island", "CC" => "Cocos (Keeling) Islands", "CO" => "Colombia", "KM" => "Comoros", "CG" => "Congo", "CD" => "Congo, The Democratic Republic Of The", "CK" => "Cook Islands", "CR" => "Costa Rica", "CI" => "Cote D'Ivoire", "HR" => "Croatia (Local Name: Hrvatska)", "CU" => "Cuba", "CY" => "Cyprus", "CZ" => "Czech Republic", "DK" => "Denmark", "DJ" => "Djibouti", "DM" => "Dominica", "DO" => "Dominican Republic", "TP" => "East Timor", "EC" => "Ecuador", "EG" => "Egypt", "SV" => "El Salvador", "GQ" => "Equatorial Guinea", "ER" => "Eritrea", "EE" => "Estonia", "ET" => "Ethiopia", "FK" => "Falkland Islands (Malvinas)", "FO" => "Faroe Islands", "FJ" => "Fiji", "FI" => "Finland", "FR" => "France", "FX" => "France, Metropolitan", "GF" => "French Guiana", "PF" => "French Polynesia", "TF" => "French Southern Territories", "GA" => "Gabon", "GM" => "Gambia", "GE" => "Georgia", "DE" => "Germany", "GH" => "Ghana", "GI" => "Gibraltar", "GR" => "Greece", "GL" => "Greenland", "GD" => "Grenada", "GP" => "Guadeloupe", "GU" => "Guam", "GT" => "Guatemala", "GN" => "Guinea", "GW" => "Guinea-Bissau", "GY" => "Guyana", "HT" => "Haiti", "HM" => "Heard And Mc Donald Islands", "VA" => "Holy See (Vatican City State)", "HN" => "Honduras", "HK" => "Hong Kong", "HU" => "Hungary", "IS" => "Iceland", "IN" => "India", "ID" => "Indonesia", "IR" => "Iran (Islamic Republic Of)", "IQ" => "Iraq", "IE" => "Ireland", "IL" => "Israel", "IT" => "Italy", "JM" => "Jamaica", "JP" => "Japan", "JO" => "Jordan", "KZ" => "Kazakhstan", "KE" => "Kenya", "KI" => "Kiribati", "KP" => "Korea, Democratic People's Republic Of", "KR" => "Korea, Republic Of", "KW" => "Kuwait", "KG" => "Kyrgyzstan", "LA" => "Lao People's Democratic Republic", "LV" => "Latvia", "LB" => "Lebanon", "LS" => "Lesotho", "LR" => "Liberia", "LY" => "Libyan Arab Jamahiriya", "LI" => "Liechtenstein", "LT" => "Lithuania", "LU" => "Luxembourg", "MO" => "Macau", "MK" => "Macedonia, Former Yugoslav Republic Of", "MG" => "Madagascar", "MW" => "Malawi", "MY" => "Malaysia", "MV" => "Maldives", "ML" => "Mali", "MT" => "Malta", "MH" => "Marshall Islands", "MQ" => "Martinique", "MR" => "Mauritania", "MU" => "Mauritius", "YT" => "Mayotte", "MX" => "Mexico", "FM" => "Micronesia, Federated States Of", "MD" => "Moldova, Republic Of", "MC" => "Monaco", "MN" => "Mongolia", "MS" => "Montserrat", "MA" => "Morocco", "MZ" => "Mozambique", "MM" => "Myanmar", "NA" => "Namibia", "NR" => "Nauru", "NP" => "Nepal", "NL" => "Netherlands", "AN" => "Netherlands Antilles", "NC" => "New Caledonia", "NZ" => "New Zealand", "NI" => "Nicaragua", "NE" => "Niger", "NG" => "Nigeria", "NU" => "Niue", "NF" => "Norfolk Island", "MP" => "Northern Mariana Islands", "NO" => "Norway", "OM" => "Oman", "PK" => "Pakistan", "PW" => "Palau", "PA" => "Panama", "PG" => "Papua New Guinea", "PY" => "Paraguay", "PE" => "Peru", "PH" => "Philippines", "PN" => "Pitcairn", "PL" => "Poland", "PT" => "Portugal", "PR" => "Puerto Rico", "QA" => "Qatar", "RE" => "Reunion", "RO" => "Romania", "RU" => "Russian Federation", "RW" => "Rwanda", "KN" => "Saint Kitts And Nevis", "LC" => "Saint Lucia", "VC" => "Saint Vincent And The Grenadines", "WS" => "Samoa", "SM" => "San Marino", "ST" => "Sao Tome And Principe", "SA" => "Saudi Arabia", "SN" => "Senegal", "SC" => "Seychelles", "SL" => "Sierra Leone", "SG" => "Singapore", "SK" => "Slovakia (Slovak Republic)", "SI" => "Slovenia", "SB" => "Solomon Islands", "SO" => "Somalia", "ZA" => "South Africa", "GS" => "South Georgia, South Sandwich Islands", "ES" => "Spain", "LK" => "Sri Lanka", "SH" => "St. Helena", "PM" => "St. Pierre And Miquelon", "SD" => "Sudan", "SR" => "Suriname", "SJ" => "Svalbard And Jan Mayen Islands", "SZ" => "Swaziland", "SE" => "Sweden", "CH" => "Switzerland", "SY" => "Syrian Arab Republic", "TW" => "Taiwan", "TJ" => "Tajikistan", "TZ" => "Tanzania, United Republic Of", "TH" => "Thailand", "TG" => "Togo", "TK" => "Tokelau", "TO" => "Tonga", "TT" => "Trinidad And Tobago", "TN" => "Tunisia", "TR" => "Turkey", "TM" => "Turkmenistan", "TC" => "Turks And Caicos Islands", "TV" => "Tuvalu", "UG" => "Uganda", "UA" => "Ukraine", "AE" => "United Arab Emirates", "UM" => "United States Minor Outlying Islands", "UY" => "Uruguay", "UZ" => "Uzbekistan", "VU" => "Vanuatu", "VE" => "Venezuela", "VN" => "Viet Nam", "VG" => "Virgin Islands (British)", "VI" => "Virgin Islands (U.S.)", "WF" => "Wallis And Futuna Islands", "EH" => "Western Sahara", "YE" => "Yemen", "YU" => "Yugoslavia", "ZM" => "Zambia", "ZW" => "Zimbabwe" ); public function display_countries() { asort($this->world_countriess); foreach ($this->world_countries as $key => $value) { echo $key . ' > <a target="_blank" href="https://www.google.se/?gws_rd=cr#fp=bac353e51a633d27&q=' . $value . '">' . $value . '</a><br>'; } } public function eeti_world_options($args) { asort($this->world_countries); $outout = '<select name="country">'; foreach ($this->world_countries as $key => $value) { if ($this->$value == $args) { $outout .= '<option value="' . $key . '" selected>' . $value . '</option>'; } else { $outout .= '<option value="' . $key . '">' . $value . '</option>'; } } $outout .= '</select>'; return $outout; } } ?> <?php $world = new World(); if (isset($_POST['submit'])) { } ?> <form method="post" action="class-world.php"> <?php echo $world->eeti_world_options('Uganda'); ?> <input type="submit" name="submit"> </form>
  6. Hey peps, I'm a bit of a noob a php so please be gentle, The following code is an associated array which takes info form a search engine such as url,title and snippet, $blekkoArray = array(); $find = array ('http://','https://','www.'); $score = 100; foreach ($js->RESULT as $item) { $blekkoArray[str_replace ($find, '', ($item->{'url'}))] = array( 'title'=> $item->{'url_title'}, 'snippet' => $item->{'snippet'}, 'score' => $score-- ); } when I do a print_r this is the output I get Array ( [example.com] => Array ( [title] => Example title [snippet] => Blah Blah Blah [score] => 100 ) [example2.com] => Array ( [title] => Example title2 [snippet] => Blah Blah Blah2 [score] => 99) [example3.com] => Array ( [title] => Example title3 [snippet] => Blah Blah Blah3 [score] => 98 ) .......) I'm trying to get an output like the following below example.com // I would like this to be a href clickable link Example title Blah Blah Blah example.com 2 Example title Blah Blah Blah 2 and so on, this is the code I've tried foreach ($js->RESULT as $item) { echo "<href={$blekkoArray[str_replace ($find, '', ($item->{'url'}))]}>". $blekkpArray[$key]['title'] . "</a> <br>" . $blekkoArray[str_replace ($find, '', ($item->{'url'}))] . "<br>" . $blekkoArray[$key]['snippet']; echo "<br>"; echo "<br>"; } but when I run the code I'm getting undifined index and undifined variable warnings, can anyone help please
  7. I have the following arrays: //$this->links is an array with the following Array ( [-1] => Array ( [text] => Home [url] => pages/HOME.htm ) [1] => Array ( [text] => About us [url] => pages/About_us.htm ) [2] => Array ( [text] => Services [url] => pages/Services.htm ) [3] => Array ( [text] => Portfolio [url] => pages/Portfolio.htm ) [4] => Array ( [text] => FAQs [url] => pages/FAQs.htm ) [5] => Array ( [text] => Contact Us [url] => pages/Contact_Us.htm ) ) //$this->PrItems is an array with the following Array ( [1] => 886_P [2] => 962_P ) //$this->chiItems is an array with the following Array ( [1] => Array ( [886_P] => Array ( [959_P] => Array ( [text] => Overview [url] => pages/Overview.htm ) [960_P] => Array ( [text] => Directors [url] => pages/Directors.htm ) [961_P] => Array ( [text] => Representatives [url] => pages/Representatives.htm ) ) ) [2] => Array ( [962_P] => Array ( [965_P] => Array ( [text] => Custom Designed Homes [url] => pages/Custom_Designed_Homes.htm ) [966_P] => Array ( [text] => Pre-Designed Homes [url] => pages/Pre-Designed_Homes.htm ) [967_P] => Array ( [text] => Ready to Occupy [url] => pages/Ready_to_Occupy.htm ) ) ) ) To get to [text] => Directors i get backwards as follows: [960_P] then [886_P] then [1] in $this->PrItems THEN match [1] (parent above ) with [1] in $this->links to get [text] => About us I wanted to achieve a result like (using above): About Us .:. Directors Like a Breadcrumb What i have tried is: foreach($this->links as $Lnkkey=>$val) { if(strtolower($val['text']) == $page) { //$ParentId=$Lnkkey; echo '<li class="active"><a href="#" onclick="return false;" >'.@$val['text'].'</a></li>'; } else { $breadcrumb='<li class="active"><a href="#" onclick="return false;" >'.@$val['text'].'</a></li>'; $parentkey = find_parent($this->chItems, $page); echo $parentkey; } } function find_parent($array, $needle, $parent = null) { foreach ($array as $key => $value) { if (is_array($value)) { $pass = $parent; if (is_string($key)) { $pass = $key; } $found = find_parent($value, $needle, $pass); if ($found !== false) { return $found; } } else if ($key === 'text' && $value === $needle) { return $parent; } } return false; } thanks in advance
  8. I want to add to an array when each recursive function is called. I have played around with it a few ways, but just getting error after error. This is about where I am up to, it should be enough to work out what I am trying to accomplish. function structure($x, $structure = array()) { $qry = mysql_query("SELECT `parent_id` FROM `categories` WHERE `categories_id`=$x"); $result = mysql_fetch_assoc($qry); $cat = $result['parent_id']; if($cat !=0) { structure($cat, $structure[] = $cat); } echo $cat.' >'; return $structure; } echo structure(22); var_dump($structure); So I am also trying to return the array as well, unsuccessfully. I am not sure how you return an array from a function either. So I would appreciate help on how to add to an array with each recursive function and return the array outside of the function into a useable variable.
  9. I think I'm starting to wrap my mind around how to work with OOP - Objects and Arrays I have starting a small test php file that I'm doing testing on. Here's my main file <?php require('includes/Connect.MySQL.Class.php'); ?> <?php require('includes/TopicFileClass.php'); ?> <?php $data = array(); // New instance/modifier of class MemberTopic $topic = new MemberTopic($data); // Retrieve topics from mysqli database $topic = $topic->retrieve_record(); //print_r($topic); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Object Oriented Programming</title> </head> <?php ?> <body> <?php foreach ($topic as $key=>$record) { // Loop through the Array to pull out the objects(records)?> <h1><?php echo $record->blog_name; // Display the Title of the Blog ?></h1> <p><?php echo $record->content; // Display the Content of the Blog ?></p> <?php } // Closes the foreach loop ?> </body> </html> An here is where I retrieve my data <?php require_once ("Connect.MySQL.Class.php"); class MemberTopic extends ConnectMySQLClass { protected $threads = array(); protected function main_record() { $database = parent::connect(); //Connects to the mysqli Database $query = "SELECT * FROM pages ORDER by id"; $result = $database->query($query); while ($page = $result->fetch_array(MYSQLI_ASSOC)) { $this->threads[] = (object) $page; } /* free result set */ $result->free(); //print_r($this->threads); return $this->threads; } public function retrieve_record() { //return $records = $this->assign_topic_record(); return $this->main_record(); } } My questions is there a way to make it so I have each object tied to a user name instead of a number? I tried doing $this->threads[$page['username']] = (object) $page; which only worked partially for it skip a few records(objects). If there isn't a way of doing it, it's no big deal for this has simplified my code a lot and makes it so much easier following what the code is doing. Thanks John
  10. Hey, I am new to learning PHP and I am trying to echo out an array using a function, but its just displaying "array" Can someone please tell me what am i doing incorrectly? Thanks! <?php function get_stores() { $store_array = array(); $stores = array('store1','store2'); foreach ($stores as $store_temp) { $store_array[] = $store_temp; } return $store_array; } echo get_stores(); ?>
  11. Hello, I have a large form that can be built dynamically, user can add multiple fields and now I have problems with saving values to DB. I'm using codeigniter. This is my form and this is part of my controller that handle those inputs: $from = array(); foreach ($this->input->post('from') as $froms) { $from[] = $froms; } $to = array(); foreach ($this->input->post('to') as $tos) { $to[] = $tos; } $step = array(); foreach ($this->input->post('step') as $steps) { $step[] = $steps; } $odvisnost = array(); foreach ($this->input->post('odvisnost') as $dependency) { $odvisnost[] = $dependency; } And I get error: and 1st value is "productid" As you can see it tries to insert 'array' instead of values that I enter, I entered 2,3,4,5 and 6. My html form is correct with all inputs names as array[] for example: <input type="text" name="steps[]">
  12. I apologize ahead of time if the code I post is too large. I did not see any posts regarding code length. I have the following array, that I created to be traversed and have specific parts passed into specific functions. $options = array( 'navigation' => array( 'page_title' => __('Aisis', 'aisis'), 'menu_title' => __('Aisis', 'aisis'), 'capabillity' => 'edit_themes', 'menu_slug' => 'aisis-core-options', 'function' => 'some_function', 'icon_url' => '', 'position' => '', 'sub_menues' => array( array( 'page_title' => __('Aisis', 'aisis'), 'menu_title' => __('Aisis', 'aisis'), 'capabillity' => 'edit_themes', 'menu_slug' => 'aisis-core-options', 'function' => 'some_function', ), array( 'page_title' => __('Aisis', 'aisis'), 'menu_title' => __('Aisis', 'aisis'), 'capabillity' => 'edit_themes', 'menu_slug' => 'aisis-core-options', 'function' => 'some_function', ), ) ), ); There are two main functions here that will be used add_menu_page() for the $options['navigation'] and add_submenu_page() for the $options['navigation']['submenues'] (yes I know there's a spelling mistake in submenues). The following code is a mess, how ever does almost what I need. Please bare with me, as It's no where near a finished product: foreach($options as $setting=>$option){ if($setting == 'navigation' && is_array($option)){ if(isset($option[$k])){ echo $option['page_title']; } foreach($option as $k=>$v){ if(is_array($v)){ foreach($v as $sub_menu){ foreach($sub_menu as $sk=>$sv){ if(isset($sub_menu[$sk])){ echo $sub_menu['menu_slug']; } } } } } } } Now what you'll see is something like echo $sub_menu['menu_slug'] - well, what if that key is not set? simple enough you say: if(isset($sub_menu['menu_slug'])){}else{} accept not, because this is where the functions come in handy, each key represents a value which is an argument for the function. no the function does not take an array of arguments, so, the question is: How do I take the array above and the code provided and do something like: foreach($option as $k=>$v){ if(is_array($v)){ foreach($v as $sub_menu){ foreach($sub_menu as $sk=>$sv){ if(isset($sub_menu[$sk])){ add_submenu_page($sub_menu['menu_slug'] /*...and so on....*/) } } } } } with out having to do a bunch of if is set, do this, else do that.I have to be able to pass in each individual key as a argument to the respected functions listed above, but I don't want to have to do a bunch of isset statements. I was thinking of doing something like in_array, or creating a walker that would look for the functions arguments. In case your wondering what the functions arguments are, look at the keys. they are the arguments, the values are the arguments values. So this is where I ask the community, what do I do? is there a simpler, cleaner way to achieve what I want?
  13. Hello there. I'm a web designer trying to learn more development skills. I've written this opening hours widget for wordpress. Its functionality is very simple which is all I really need and it does the job, however I'd love to know how to make the code smaller as there are lots of thing repeating. I think parts of it could be done using a for each loop and arrays, but I can't figure out what way to do it. If anyone can help or point me in the right direction for what topic specifically to study I would be very grateful. Please see code below. Sorry if its really badly written, /** * Creating and displaying an Opening Times Widget */ wp_register_sidebar_widget( 'opening_times_widget', // your unique widget id 'Opening Times', // widget name 'opening_times_widget_display', // callback function to display widget array( // options 'description' => 'This widget displays your opening hours in your website sidebar' ) ); wp_register_widget_control( 'opening_times_widget', // id 'opening_times_widget', // name 'opening_times_widget_control' // callback function ); function opening_times_widget_control($args=array(), $params=array()) { //the form is submitted, save into database if (isset($_POST['submitted'])) { update_option('opening_times_widget_title', $_POST['widgettitle']); update_option('opening_times_widget_email', $_POST['widgetemail']); update_option('opening_times_widget_description', $_POST['description']); update_option('opening_times_widget_monday', $_POST['mondayhours']); update_option('opening_times_widget_tuesday', $_POST['tuesdayhours']); update_option('opening_times_widget_wednesday', $_POST['wednesdayhours']); update_option('opening_times_widget_thursday', $_POST['thursdayhours']); update_option('opening_times_widget_friday', $_POST['fridayhours']); update_option('opening_times_widget_saturday', $_POST['saturdayhours']); update_option('opening_times_widget_sunday', $_POST['sundayhours']); } //load options $widgettitle = get_option('opening_times_widget_title'); $widgetemail = get_option('opening_times_widget_email'); $description = get_option('opening_times_widget_description'); $mondayhours = get_option('opening_times_widget_monday'); $tuesdayhours = get_option('opening_times_widget_tuesday'); $wednesdayhours = get_option('opening_times_widget_wednesday'); $thursdayhours = get_option('opening_times_widget_thursday'); $fridayhours = get_option('opening_times_widget_friday'); $saturdayhours = get_option('opening_times_widget_saturday'); $sundayhours = get_option('opening_times_widget_sunday'); ?> Widget Title: ( eg: Opening Hours )<br /> <input type="text" class="widefat" name="widgettitle" value="<?php echo stripslashes($widgettitle); ?>" /> <br /><br /> Monday<br /> <input type="text" class="widefat" name="mondayhours" value="<?php echo stripslashes($mondayhours); ?>" /> <br /><br /> Tuesday<br /> <input type="text" class="widefat" name="tuesdayhours" value="<?php echo stripslashes($tuesdayhours); ?>" /> <br /><br /> Wednesday<br /> <input type="text" class="widefat" name="wednesdayhours" value="<?php echo stripslashes($wednesdayhours); ?>" /> <br /><br /> Thursday<br /> <input type="text" class="widefat" name="thursdayhours" value="<?php echo stripslashes($thursdayhours); ?>" /> <br /><br /> Friday<br /> <input type="text" class="widefat" name="fridayhours" value="<?php echo stripslashes($fridayhours); ?>" /> <br /><br /> Saturday<br /> <input type="text" class="widefat" name="saturdayhours" value="<?php echo stripslashes($saturdayhours); ?>" /> <br /><br /> Sunday<br /> <input type="text" class="widefat" name="sundayhours" value="<?php echo stripslashes($sundayhours); ?>" /> <br /><br /> Additional Information:<br /> <textarea class="widefat" rows="5" name="description"><?php echo stripslashes($description); ?></textarea> <br /><br /> Email Address:<br /> <input type="text" class="widefat" name="widgetemail" value="<?php echo stripslashes($widgetemail); ?>" /> <br /><br /> <input type="hidden" name="submitted" value="1" /> <?php } function opening_times_widget_display($args=array(), $params=array()) { //load options $widgettitle = get_option('opening_times_widget_title'); $description = get_option('opening_times_widget_description'); $widgetemail = get_option('opening_times_widget_email'); $mondayhours = get_option('opening_times_widget_monday'); $tuesdayhours = get_option('opening_times_widget_tuesday'); $wednesdayhours = get_option('opening_times_widget_wednesday'); $thursdayhours = get_option('opening_times_widget_thursday'); $fridayhours = get_option('opening_times_widget_friday'); $saturdayhours = get_option('opening_times_widget_saturday'); $sundayhours = get_option('opening_times_widget_sunday'); //widget output echo stripslashes($args['before_widget']); echo stripslashes($args['before_title']); echo stripslashes($widgettitle).'<span class="opening-hours-icon"> </span>'; echo stripslashes($args['after_title']); echo '<div class="textwidget">'; if ($mondayhours != '') { echo '<div class="opening-hours-day-info">Monday: <span>'.stripslashes($mondayhours).'</span></div>'; } if ($tuesdayhours != '') { echo '<div class="opening-hours-day-info">Tuesday: <span>'.stripslashes($tuesdayhours).'</span></div>'; } if ($wednesdayhours != '') { echo '<div class="opening-hours-day-info">Wednesday: <span>'.stripslashes($wednesdayhours).'</span></div>'; } if ($thursdayhours != '') { echo '<div class="opening-hours-day-info">Thursday: <span>'.stripslashes($thursdayhours).'</span></div>'; } if ($fridayhours != '') { echo '<div class="opening-hours-day-info">Friday: <span>'.stripslashes($fridayhours).'</span></div>'; } if ($saturdayhours != '') { echo '<div class="opening-hours-day-info">Saturday: <span>'.stripslashes($saturdayhours).'</span></div>'; } if ($sundayhours != '') { echo '<div class="opening-hours-day-info">Sunday: <span>'.stripslashes($sundayhours).'</span></div>'; } echo '<div class="opening-hours-description">'.stripslashes(nl2br($description)).'</div>'; if ($widgetemail != '') { echo '<div class="opening-hours-email"><a href="mailto:'.stripslashes($widgetemail).'" target="_blank">Email us</a> to arrange an appointment</div>'; } echo '</div>';//close div.textwidget echo stripslashes($args['after_widget']); }
  14. I looking for a good tutorial that will cover arrays, from HTML forms to storing the data( serialize,unserialize, implode, explode)in mysql with php I need to create a from that will allow me to create an array from text field then submit to database and late allow me to editied and update that array So I have four basic tables one serving as main table that will hold 5 field of data plus three field set aside for arrays then I have 3 tables that will hold keys and reference for those array plus additional data objective : In my main table the fields array1 array2 and array3 are the one I need to insert the array data into. I need to be able to manipulate the data of the array completely from an HTML form or multiple forms create basic HTML forms and PHP code to process I must be able to pull a record, check to see if that is an in those field array then add some data if their is if not start a new array for that record create basic HTML forms and PHP code to process I must be able to view and delete part of the array as well create basic HTML forms and PHP code to process then pull a record that has array data in it, then create a query base on those array to pull data from other tables and create some basic calculation base on the original record and the data that you reference in the other tables ( tables array1 array2 and array3 )create basic HTML forms and PHP code to process To help paint you better picture I am attaching below some sample tables and data I know that the data is not optimize but that is on purpose ok let say that this is( id) 2 in main 2 11 12 12 15 18 ('MOPQY4IV','9QR4TH7K','NZ1O45B0','1XUUU5D4','J94RVSNY')NULL NULL this array would be reference in table array1 'MOPQY4IV','9QR4TH7K','NZ1O45B0','1XUUU5D4','J94RVSNY' So in PHP I need to create a for loop that would take the value of this array and pull the data from table array1 I don't think the foreign key would work as this is not normalize database since other (id) in main could reference the same keys in array1 so I believe it be a many to many relation (id)3 could look some like this 3 10 16 12 17 14 ('MOPQY4IV','9QR4TH7K','JAM39TXN',)NULL NULL some of the array value are the same as in (id) 2 Thank You Antonio CREATE TABLE IF NOT EXISTS `array1` ( `id` int(11) NOT NULL AUTO_INCREMENT, `arrayKey` varchar( NOT NULL, `data1` int(11) NOT NULL, `data2` int(11) NOT NULL, `data3` int(11) NOT NULL, `data4` int(11) NOT NULL, `data5` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; -- -- Dumping data for table `array1` -- INSERT INTO `array1` (`id`, `arrayKey`, `data1`, `data2`, `data3`, `data4`, `data5`) VALUES (1, 'MOPQY4IV', 0, 1, 0, 3, 2), (2, '9QR4TH7K', 2, 2, 0, 0, 2), (3, '8NBYRZ72', 2, 1, 3, 3, 3), (4, 'NZ1O45B0', 0, 2, 2, 3, 2), (5, 'Y7XPA7Q3', 0, 0, 1, 1, 2), (6, '1XUUU5D4', 1, 3, 2, 1, 2), (7, 'JVUI1KA6', 2, 1, 3, 3, 1), (8, 'J94RVSNY', 3, 2, 3, 1, 1), (9, 'NF9YSEF4', 2, 3, 0, 1, 3), (10, 'LFY81TBA', 1, 1, 1, 3, 1), (11, 'LZH9S2DE', 0, 3, 2, 0, 1), (12, '7XK4NF8M', 3, 1, 1, 2, 0), (13, 'JAM39TXN', 0, 0, 2, 2, 1); -- -------------------------------------------------------- -- -- Table structure for table `array2` -- CREATE TABLE IF NOT EXISTS `array2` ( `id` int(11) NOT NULL AUTO_INCREMENT, `arrayKey` varchar( NOT NULL, `data1` int(11) NOT NULL, `data2` int(11) NOT NULL, `data3` int(11) NOT NULL, `data4` int(11) NOT NULL, `data5` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; -- -- Dumping data for table `array2` -- INSERT INTO `array2` (`id`, `arrayKey`, `data1`, `data2`, `data3`, `data4`, `data5`) VALUES (1, 'BZGZX887', 1, 0, 0, 0, 3), (2, 'WW7JG2WI', 3, 1, 0, 2, 0), (3, 'U1UAK4Z7', 0, 2, 2, 3, 0), (4, 'L1ETC8VM', 1, 3, 3, 3, 3), (5, 'RYPO75Y6', 3, 3, 0, 1, 0), (6, 'O9XKS4B0', 2, 2, 2, 2, 0), (7, 'A1W8VD5M', 1, 1, 0, 3, 3), (8, '4EH4IUBF', 1, 3, 3, 2, 0), (9, '2YV7VJML', 0, 2, 0, 1, 1), (10, '1V9TPRT8', 1, 2, 3, 3, 1), (11, '6XC0QJPB', 1, 2, 2, 3, 3), (12, 'JWX4SG1M', 2, 2, 3, 1, 0), (13, '60UBRIB2', 0, 0, 2, 2, 0); -- -------------------------------------------------------- -- -- Table structure for table `array3` -- CREATE TABLE IF NOT EXISTS `array3` ( `id` int(11) NOT NULL AUTO_INCREMENT, `arrayKey` varchar( NOT NULL, `data1` int(11) NOT NULL, `data2` int(11) NOT NULL, `data3` int(11) NOT NULL, `data4` int(11) NOT NULL, `data5` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ; -- -- Dumping data for table `array3` -- INSERT INTO `array3` (`id`, `arrayKey`, `data1`, `data2`, `data3`, `data4`, `data5`) VALUES (1, 'XW2R8FZV', 0, 2, 0, 2, 1), (2, 'U0UQ4XE0', 3, 3, 3, 2, 1), (3, 'DJZ0F72P', 0, 2, 0, 2, 1), (4, '58NZG2QT', 3, 0, 3, 1, 0), (5, '8X0MTA7C', 3, 3, 1, 3, 0), (6, '566JPHPO', 3, 1, 0, 2, 2), (7, '59FE3PVA', 3, 0, 2, 3, 1), (8, 'O87PI80J', 1, 2, 0, 3, 3), (9, 'J69OP30N', 1, 2, 0, 2, 2), (10, '4VCA5FA9', 2, 1, 1, 3, 3), (11, 'N6I82WQS', 2, 0, 3, 0, 2), (12, 'ZSNV3O7K', 0, 0, 2, 2, 3), (13, 'YE6E4RB0', 2, 2, 3, 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `main` -- CREATE TABLE IF NOT EXISTS `main` ( `id` int(11) NOT NULL AUTO_INCREMENT, `data1` int(11) NOT NULL, `data2` int(11) NOT NULL, `data3` int(11) NOT NULL, `data4` int(11) NOT NULL, `data5` int(11) NOT NULL, `array1` text, `array2` text, `array3` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; -- -- Dumping data for table `main` -- INSERT INTO `main` (`id`, `data1`, `data2`, `data3`, `data4`, `data5`, `array1`, `array2`, `array3`) VALUES (1, 10, 11, 15, 14, 16, NULL, NULL, NULL), (2, 11, 12, 12, 15, 18, NULL, NULL, NULL), (3, 10, 16, 12, 17, 14, NULL, NULL, NULL), (4, 18, 10, 13, 16, 11, NULL, NULL, NULL), (5, 11, 10, 13, 9, 15, NULL, NULL, NULL), (6, 9, 18, 14, 17, 14, NULL, NULL, NULL), (7, 14, 18, 16, 13, 17, NULL, NULL, NULL), (8, 15, 16, 12, 17, 17, NULL, NULL, NULL), (9, 17, 16, 12, 14, 10, NULL, NULL, NULL), (10, 17, 14, 11, 9, 17, NULL, NULL, NULL), (11, 12, 18, 10, 13, 13, NULL, NULL, NULL), (12, 10, 12, 14, 14, 10, NULL, NULL, NULL), (13, 14, 14, 12, 17, 18, NULL, NULL, NULL), (14, 1, 1, 1, 1, 1, NULL, NULL, NULL), (15, 22, 22, 22, 22, 22, NULL, NULL, NULL), (16, 1, 1, 1, 1, 1, NULL, NULL, NULL);
  15. I have this array: Array ( [978_P] => Array( [986_P] => Array( [text] => Kenya [url] => /www/kilele/pages/Kenya.htm) [987_P] => Array( [text] => Tanzania National Parks [url] => /www/kilele/pages/Tanzania_National_Parks.htm) [988_P] => Array( [text] => Uganda National Parks [url] => /www/kilele/pages/Uganda_National_Parks.htm) ) [986_P] => Array( [989_P] => Array( [text] => Child1 [url] => /www/kilele/pages/Child1.htm) ) [990_P] => Array( [text] => Child2 [url] => /www/kilele/pages/Child2.htm) ) ) [990_P] => Array( [991_P] => Array( [text] => GrandChild1 [url] => /www/kilele/pages/GrandChild1.htm) ) [992_P] => Array( [text] => GrandChild2 [url] => /www/kilele/pages/GrandChild2.htm) ) ) ) NOTE: [986_P] inside the [978_P] has children in the [986_P] array: Same as [990_P] inside the [986_P] has children to [990_P] which are grandchildren to [986_P]. I can loop through these arrays to get all the [text] and as follows: foreach ($this->chItems[$Lnkkey] as $Res => $ChkLynks) { //print_r($this->chItems[$Lnkkey]); foreach ($ChkLynks as $ResLynks) { echo '<li><a href="'.$ResLynks["url"].'">'.$ResLynks["text"].'</a></li>'; } } The issue is that i need to get the children under their parents and the grandchildren under their parents too. as follows: <ul> <li><a href="/www/kilele/pages/Kenya.htm "> Kenya </a> <ul> <li><a href="/www/kilele/pages/Child1.htm"> Child1</a></li> <li><a href="/www/kilele/pages/Child2.htm"> Child2 </a> <ul> <li><a href="/www/kilele/pages/GrandChild1.htm"> GrandChild1 </a></li> . . . </ul> </li> </ul> </li> <li><a href=""></a></li> . . . </ul> I tried is_object but could not get that working: Thanks in advance
  16. Hi! am trying a shortcut here: Array ([981_P] => Array([text] => why Kilele[url] => /www/kilele/pages/why_Kilele.htm) [982_P] => Array([text] => About Kenya[url] => /www/kilele/pages/About_Kenya.htm) [983_P] => Array([text] => Unique value proposition[url] => /www/kilele/pages/Unique_value_proposition.htm) [984_P] => Array([text] => About Tanzania[url] => /www/kilele/pages/About_Tanzania.htm) [985_P] => Array([text] => About Uganda[url] => /www/kilele/pages/About_Uganda.htm) ) i want to use all [text] and , without using the outer array with indexes 982_p e.t.c .? Can i merge them leaving out the first array index with 982_p, 983_p e.t.c? thanks in advace..
  17. Hello... I simply am running a query with the Twitter Search API that searches for a specific term and then returns the Tweets it finds. This is a sample of what the array of Tweets returned looks like: array(50) { [0]=> object(stdClass)#9 (18) { ["created_at"]=> string(31) "Tue, 11 Dec 2012 04:30:08 +0000" ["from_user"]=> string(7) "Cvpcake" ["from_user_id"]=> int(44610318) ["from_user_id_str"]=> string( "44610318" ["from_user_name"]=> string(6) "KILLER" ["geo"]=> NULL ["id"]=> float(2.7835596410783E+17) ["id_str"]=> string(18) "278355964107829248" ["iso_language_code"]=> string(2) "en" ["metadata"]=> object(stdClass)#10 (1) { ["result_type"]=> string(6) "recent" } ["profile_image_url"]=> string(90) "http://a0.twimg.com/profile_images/2945542955/d437253418ea0ae75efb5ae6bf5cec1e_normal.jpeg" ["profile_image_url_https"]=> string(92) "https://si0.twimg.com/profile_images/2945542955/d437253418ea0ae75efb5ae6bf5cec1e_normal.jpeg" ["source"]=> string(89) "<a href="http://twitter.com/download/iphone">Twitter for iPhone</a>" ["text"]=> string(57) "RT @DJNickatNIte_: 9 weeks test ain't got shit on #FINALS" ["to_user"]=> NULL ["to_user_id"]=> int(0) ["to_user_id_str"]=> string(1) "0" ["to_user_name"]=> NULL } [1]=> object(stdClass)#11 (18) { ["created_at"]=> string(31) "Tue, 11 Dec 2012 04:30:07 +0000" ["from_user"]=> string( "BaboTina" ["from_user_id"]=> int(224918169) ["from_user_id_str"]=> string(9) "224918169" ["from_user_name"]=> string(4) "Tina" ["geo"]=> NULL ["id"]=> float(2.783559623588E+17) ["id_str"]=> string(18) "278355962358796288" ["iso_language_code"]=> string(2) "en" ["metadata"]=> object(stdClass)#12 (1) { ["result_type"]=> string(6) "recent" } ["profile_image_url"]=> string(89) "http://a0.twimg.com/profile_images/2936213945/390fe03b68949baa1bb1af2f2d6fe76e_normal.png" ["profile_image_url_https"]=> string(91) "https://si0.twimg.com/profile_images/2936213945/390fe03b68949baa1bb1af2f2d6fe76e_normal.png" ["source"]=> string(91) "<a href="http://twitter.com/download/android">Twitter for Android</a>" ["text"]=> string(130) "RT @autocorrects: Multiple choice (test): A, B, C, or D? “Well I haven’t had a B for like 4 questions so I’ll choose that”" ["to_user"]=> NULL ["to_user_id"]=> int(0) ["to_user_id_str"]=> string(1) "0" ["to_user_name"]=> NULL } [2]=> object(stdClass)#13 (18) { ["created_at"]=> string(31) "Tue, 11 Dec 2012 04:30:07 +0000" ["from_user"]=> string(13) "SyifaGBastian" ["from_user_id"]=> int(332078990) ["from_user_id_str"]=> string(9) "332078990" ["from_user_name"]=> string(12) "ViscaELBarca" ["geo"]=> NULL ["id"]=> float(2.7835596214069E+17) ["id_str"]=> string(18) "278355962140688385" ["iso_language_code"]=> string(3) "und" ["metadata"]=> object(stdClass)#14 (1) { ["result_type"]=> string(6) "recent" } ["profile_image_url"]=> string(90) "http://a0.twimg.com/profile_images/2921649342/1a38717324614fad5993dc5e4383a925_normal.jpeg" ["profile_image_url_https"]=> string(92) "https://si0.twimg.com/profile_images/2921649342/1a38717324614fad5993dc5e4383a925_normal.jpeg" ["source"]=> string(59) "<a href="http://twitter.com/">web</a>" ["text"]=> string(4) "test" ["to_user"]=> NULL ["to_user_id"]=> int(0) ["to_user_id_str"]=> string(1) "0" ["to_user_name"]=> NULL } Now what I want to do is store the "id_str" field of each Tweet into an array. I'm trying to do this and I thought it would be simple, but I must be doing something wrong. Here is what I have, which results in an error. $tweetIds; // loop through $results and favorite them for($i=0; $i<3; $i++) { $tweetIds[$i] => $results[$i]['id_str']; } I've tried a couple of other things, including... $tweetIds; // loop through $results and favorite them for($i=0; $i<3; $i++) { $tweetIds[$i] => $results[$i]["id_str"]; } and... $tweetIds; // loop through $results and favorite them for($i=0; $i<3; $i++) { $tweetIds[$i] => $results[$i][7]; } But each way has resulted in an error. I can't figure out why. I'm sure it's something simple I'm not doing correctly... thanks for any help
  18. I am passing user inputs from a page called add_product.php. There is a drop down menu that CONCATs two table fields to form one name ($category). After passing $category to the product_created.php page, I can break this back down into the two respective fields using explode() on but how do I create variable out of the results? Here is the snippet from add_product.php <?php //Grab the Product Category name and Bucket name from productcategory and bucket tables in DB $qry=mysql_query("SELECT CONCAT(bucket.b_name, ' : ', productcategory.name) AS category FROM productcategory, bucket, product WHERE product.category_id = productcategory.id AND productcategory.bucket_id = bucket.id", $con); if(!$qry) { die("Query Failed: ". mysql_error()); } ?> <p>Category: <select name="category" id="category"> <?php //take the responses from the query above and show then in a drop down menu while($row=mysql_fetch_array($qry)) { echo $category = "<option value='".$row['category']."'>".$row['category']."</option>"; } ?> </select> I then pass that to product_created.php and this is what I have so far and where I am stuck: //This gets all the other information from the form $category=$_POST['category']; // Explode category variable to get bucket.b_name and productcategory.name list($b_name, $pc_name) = explode(":", $category); echo $b_name.'<br/>'; // bucket.b_name echo $pc_name.'<br/>'; // productcategory.name //the above code works and prints the separate category names onscreen $categories = array($b_name,$pc_name); print "The product category name is $pc_name"; //test two: this code works and prints just the productcategory name //Define the query to grab the product category id where pc_name equals the product category name $sql = "SELECT id FROM productcategory WHERE name = '$pc_name'"; //submit the query and capture the result $result = mysql_query($sql) or die(mysql_error()); echo $result; //find out how many rows were retrieved $numRows = mysql_num_rows($result); //current result is 0 and should be 1 if successful //this is my attempt to convert the productcategory id into a variable that can be passed back into the DB $sql_q = "SELECT id FROM productcategory WHERE name = '$pc_name'" or die(mysql_error()); $sql = mysql_fetch_array($sql_q); //above sets the category_id array //example usage: $sql['mysql_col_name'] echo $sql['category_id']; //the above prints the category_id foreach ($sql as $category_id) { //echo $category_id.'<br/>'; } //Define query to add product to DB $qry=mysql_query("INSERT INTO product(name,category_id,slug,old_price,price,description,video_url,status,date_posted)VALUES('$name','$category_id','$slug','$o_price','$price','$desc','$video','$status','$date')", $con); if(!$qry) { die("Query Failed: ". mysql_error()); } else { echo "<br/>"; echo "Product Added Successfully"; echo "<br/>"; } I know some of this is redundant but I am trying to teach myself how to solve this and this was the best way for me to learn. I feel like I am really close, but that I have gone round and round at this point and have just confused myself. I understand that there may be other issues with my code as it is written, but I really need to focus on resolving this first. Any help, advise, teaching, would be most appreciated.
  19. is it possible to store the keys of an array in to variables? currently my code looks like this: function getanswers() { $sql = mysql_query("select answer FROM answers WHERE question_ID= 1 "); while($row =mysql_fetch_row($sql)) { //print_r (array_keys($row)); $ans1 = $row['0']; $ans2 = $row; $ans3 = $row; $ans4 = $row; echo $ans1 . $ans2. $ans3. $ans4 ; } } and all I get are undefined offset notices what am i doing wrong? I'd appreciate any advice the output looks like this: The ‘Sea Swallow’ is an alternative name for which bird? Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 29 Notice: Undefined offset: 2 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 30 Notice: Undefined offset: 3 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 31 Seagull Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 29 Notice: Undefined offset: 2 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 30 Notice: Undefined offset: 3 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 31 Penguin Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 29 Notice: Undefined offset: 2 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 30 Notice: Undefined offset: 3 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 31 Tern Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 29 Notice: Undefined offset: 2 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 30 Notice: Undefined offset: 3 in /Applications/MAMP/htdocs/Quiz/newfile.php on line 31 Cormorant Just in case it helps when I call the array keys they show this: Array ( [0] => 0 )Array ( [0] => 0 )Array ( [0] => 0 )Array ( [0] => 0 ) Thanks in advance to anyone who can help!
  20. i have a foreach statement which looks like this foreach(static::$_components as &$field){ ..some code } in "some code" i sometimes add more components to "static::$_components" member if the insertion happens not at the final iteration it works, and the foreach detect & use the last insertion. but if the insertion happens at the last iteration the foreach statement breaks(ends) without detecting & using the last insertion there is any workaround for this issue beside using for loops and count(array). i prefer using foreach due to performance demands for($iterator = 0, $field = ''; null != ($field = empty(static::$_components[$iterator]) ? null : static::$_components[$iterator]); $iterator++){ ...some code } consumes a lot of memory and proccessing time using for($iterator = 0; $iterator < count(static::$_components); $iterator++){ ...some code } is even worse Thanks in advance
  21. Hi, I've been searching high and low for this answer all day and still no luck, so I thought I'd reach out to a fellow PHPer. If you can help I'd be most grateful! Ok here's the problem I'm trying to solve: I have a string value of; show_title=yes,show_intro=no,show_category=yes,show_print_icon=no,show_email_icon=yes I would like to split the string value in two places (removing the symbol at the same time), at the comma and at the equals. Then I'd like to put the values into an array naming each entry by the value entered before the equals symbol. Like so, show_title => yes show_intro => no show_category => yes show_print => no show_email_icon => no I'm hoping from doing this I can then easily refer to the setting I need later in my script. if ($array[show_print] == true) { you get the idea... } Thank for your time again! Matt
  22. Hello, I am fairly novice at PHP. I have a couple of reference books*, but they seem to be vague on the subject of "arrays", that is why I am asking for help today. I am trying to create a simple array using a form and radio button selectors. At the bottom I will explain what I am trying to accomplish. Here is the sample of my code using one question: HTML........................................................................................................................................................................................ <fieldset> <legend>DO YOU EXERCISE DAILY?</legend> <form action="" method="post" /> <label for="question" class="question">I often exercise on a daily basis for at least 20 minutes a day</label> <label for "Never" class="radio"> <input type="radio" name="answer[0]=1" value="Never" /> Never</label> <label for="Seldom" class="radio"> <input type="radio" name="answer[1]=2" value="Seldom" /> Seldom</label> <label for="Occasionally" class="radio"> <input type="radio" name="answer[2]=3" value="Occasionally" /> Occasionally</label> <label for="Often" class="radio"> <input type="radio" name="answer[3]=4" value="Often" /> Often</label> <label for="Always" class="radio"> <input type="radio" name="answer[4]=5" value="Always" /> Always</label> </form> </fieldset> When a question is asked, the user can choose only one (radio button) answer. That answer is assigned a number (1 thru 5) and will be displayed and then eventually tallied along with answers to other questions (not shown) for a grand total or sum. PHP.......................................................................................................................................................................................... <?php //Error Displaying ini_set ('display_errors',1); error_reporting (E_ALL & ~E_NOTICE); //Print each answer <?php if (isset($_POST["answer"]) && is_array($_POST["answer"]) && count($_POST["answer"]) > 0) { foreach ($_POST["answer"] as $answer) { echo htmlspecialchars($answer, ENT_QUOTES); echo '<br />'; } } ?> // Print each key and value. <?php $answer = array ('Never', 'Seldom', 'Occasionally', 'Often', 'Always'); foreach ($answer as $ans => $answer) { print "$ans: $answer<br />\n"; } ?> I am able to get the answer (picked via radio button) to print or echo on the page, but I am not sure how to display a number represting each choice (1 for Never ~ 5 for Always). Not sure what I am doing wrong. I have researched other examples on the web and tried their logic, still no success. I guess I am just not getting it. Any advice or help would be appreciated. Also do any of you readers recommend another book to learn from? Signed, Garfan *Murachs PHP and MYSQL *PHP For The World Wide Web by Larry Ullman
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.