Arrays in PHP
Topics
Could someone here explain me the reason for this error in detail..... FYI - i am just more than a fresher in PHP..... Code: [Select] Fatal error: Cannot use string offset as an array I've never worked with multidimensional arrays. I have developed a calendar app. Right now i have it query the db for every day. So potentially 31 queries. Two part question: Would it be better(more "optimized") to query the db once to get all the events in that month for a certain calendar and put the rows into a multidimensional array and use php to determine which events to put in what days? And if that's the case, how do you cycle through the first key in an array like the following? I'm not even sure if this is the best way to structure the array. The number's represent the id number in the db and i will need to cycle through these. Code: [Select] $events = array ( "1"=>array ( "Bob's Birthday", "2011-05-24 16:30:0", "2011-05-25 12:00:00", ), "2"=>array ( "Day Off", "2011-05-27 08:30:0", "2011-05-28 17:00:00", ), "3"=>array ( "Pay rent", "2011-06-01 08:00:0", "2011-05-01 17:00:00", ) ); //something like this...maybe? foreach($events['first_key'] as $key => $value) { // not a clue how to reference the contents } I've never used array's because I've always found a way to do something without them. I have finally taught myself how array's work, but I cannot seem to add a key and value to an array without my code creating another array inside that one. I'm not sure what I'm doing wrong, but this is what I'm getting. From what I understand, print_r is suppose to print out an array. This is what my print_r displays: Array ( [knife] => 2000 ) Array ( [baseballbat] => 2000 [knife] => 2000 ) Array ( [colt] => 2000 [knife] => 2000 [baseballbat] => 2000 ) Array ( [deserteagle] => 2000 [baseballbat] => 2000 [knife] => 2000 [colt] => 2000 ) Array ( [ingram] => 2000 [colt] => 2000 [knife] => 2000 [baseballbat] => 2000 [deserteagle] => 2000 ) Array ( [deserteagle] => 2000 [ump40] => 2000 [baseballbat] => 2000 [knife] => 2000 [colt] => 2000 [ingram] => 2000 ) Array ( [colt] => 2000 [ingram] => 2000 [deserteagle] => 2000 [knife] => 2000 [baseballbat] => 2000 [ump40] => 2000 [grenades] => 958 ) Array ( [baseballbat] => 2000 [ump40] => 2000 [colt] => 2000 [knife] => 2000 [deserteagle] => 2000 [ingram] => 2000 [grenades] => 958 ) Array ( [deserteagle] => 2000 [ingram] => 2000 [baseballbat] => 2000 [knife] => 2000 [colt] => 2000 [ump40] => 2000 [grenades] => 958 ) Array ( [colt] => 2000 [ump40] => 2000 [deserteagle] => 2000 [knife] => 2000 [baseballbat] => 2000 [ingram] => 2000 [grenades] => 958 ) Array ( [baseballbat] => 2000 [ingram] => 2000 [colt] => 2000 [knife] => 2000 [deserteagle] => 2000 [ump40] => 2000 [grenades] => 958 ) Array ( [deserteagle] => 2000 [ump40] => 2000 [baseballbat] => 2000 [knife] => 2000 [colt] => 2000 [ingram] => 2000 [grenades] => 958 ) Array ( [colt] => 2000 [ingram] => 2000 [deserteagle] => 2000 [knife] => 2000 [baseballbat] => 2000 [ump40] => 2000 [grenades] => 958 ) Array ( [baseballbat] => 2000 [ump40] => 2000 [colt] => 2000 [knife] => 2000 [deserteagle] => 2000 [ingram] => 2000 [grenades] => 958 ) Array ( [deserteagle] => 2000 [ingram] => 2000 [baseballbat] => 2000 [knife] => 2000 [colt] => 2000 [ump40] => 2000 [grenades] => 958 ) Array ( [ump40] => 2000 [pepperspray] => 2000 [colt] => 2000 [knife] => 2000 [ingram] => 2000 [baseballbat] => 2000 [deserteagle] => 2000 [grenades] => 958 ) Array ( [baseballbat] => 2000 [deserteagle] => 2000 [flashbangs] => 2000 [ump40] => 2000 [ingram] => 2000 [pepperspray] => 2000 [colt] => 2000 [knife] => 2000 [grenades] => 958 ) Array ( [pepperspray] => 2000 [colt] => 2000 [knife] => 2000 [baseballbat] => 2000 [ingram] => 2000 [ump40] => 2000 [deserteagle] => 2000 [flashbangs] => 2000 [teargas] => 1800 [grenades] => 958 ) Array ( [pepperspray] => 2000 [deserteagle] => 2000 [flashbangs] => 2000 [ingram] => 2000 [ump40] => 2000 [baseballbat] => 2000 [colt] => 2000 [knife] => 2000 [tasergun] => 1800 [teargas] => 1800 [grenades] => 958 ) Array ( [pepperspray] => 2000 [colt] => 2000 [knife] => 2000 [ump40] => 2000 [baseballbat] => 2000 [ingram] => 2000 [deserteagle] => 2000 [flashbangs] => 2000 [teargas] => 1800 [tasergun] => 1800 [combathelmet] => 1600 [grenades] => 958 ) Array ( [ingram] => 2000 [pepperspray] => 2000 [flashbangs] => 2000 [baseballbat] => 2000 [deserteagle] => 2000 [ump40] => 2000 [colt] => 2000 [knife] => 2000 [tasergun] => 1800 [teargas] => 1800 [combathelmet] => 1600 [grenades] => 958 [kevlarvest] => 271 ) Array ( [ump40] => 2000 [ingram] => 2000 [knife] => 2000 [deserteagle] => 2000 [colt] => 2000 [baseballbat] => 2000 [pepperspray] => 2000 [flashbangs] => 2000 [teargas] => 1800 [tasergun] => 1800 [combathelmet] => 1600 [grenades] => 958 [kevlarvest] => 271 ) Array ( [baseballbat] => 2000 [ump40] => 2000 [flashbangs] => 2000 [colt] => 2000 [pepperspray] => 2000 [deserteagle] => 2000 [ingram] => 2000 [knife] => 2000 [tasergun] => 1800 [teargas] => 1800 [combathelmet] => 1600 [grenades] => 958 [kevlarvest] => 271 ) Array ( [deserteagle] => 2000 [baseballbat] => 2000 [knife] => 2000 [pepperspray] => 2000 [ingram] => 2000 [colt] => 2000 [ump40] => 2000 [flashbangs] => 2000 [teargas] => 1800 [tasergun] => 1800 [combathelmet] => 1600 [grenades] => 958 [kevlarvest] => 271 ) Notice how the first array has one key/value, the second has the same value as the first plus an additional value. The third array has the same values as the second array plus an additional value. I'm confused as to whether my array is correct, and that print_t is just showing me how the array has changed everytime the while loop went through, or there is an error in my code and my array is not correct. I want to get this cleared before I continue. Here is my code so far: Code: [Select] <? $user = $_GET['user']; $attacks = $_GET['attacks']; $quser = mysql_query("SELECT * FROM user WHERE username = '$user'"); $nuser = mysql_num_rows($quser); if ($nuser == 1) { $ruser = mysql_fetch_array($quser); $totalpower = $ruser[power] + $ruser[defense]; $sabpower = round ($totalpower * $sabdmg); $ramount = mysql_fetch_array(mysql_query("SELECT * FROM user_items WHERE username = '$user'")); $wa = array(); $qweps = mysql_query("SELECT * FROM weaponstore ORDER BY type ASC, price ASC"); while ($rweps = mysql_fetch_array($qweps)) { $wepname = $rweps[colname]; $wepamount = $ramount[$wepname]; if ($wepamount >= 1) { $wa[$wepname] = $wepamount; } arsort($wa); print_r($wa); } } ?> Basically the code should add the $wepname as the key and $wepamount as the value to an array $wa only if $wepamount is >= 1, but the way my print_r is showing it I'm just confused as to why I'm getting a bunch of arrays and not just one. hi phpfreaks, I want change the last value when iterating through an array but I can't seem to get to work. I can never get to the echo housing but can't work out why any advice would be great. Code: [Select] foreach ($headings as $key => $cValues){ $cols .= $key.","; if(current($headings)== count($headings)){ echo "housing"; $cols .= $key; break; } } Hello, how could I do a replace using one array? Example: Code: [Select] $changes = array( "{NAME}" => $name, "{CHANGED_PART}" => $desc, "{CHANGE_D}" => date("j"), "{CHANGE_M}" => date("n") ); And then I would want to replace all parts in the left with parts in the right inside a string.Is that possible ? thank you.. Good Evening, I'm having no luck in something that I'm sure is incredibly simply... If I have an array like the following... Code: [Select] $array = array(15,22,0,43,0,6);How can I find and replace all the zeros with a one? Regards, Ace i have the following array $fruits = array("cherry" => "red", "apple" => "red", "kiwi" => "green", "strawberry" => "red", "pear" => "yellow", "melon" => "green", "grapes" => "green", "watermelon" => "red", "banana" => "yellow") using the array_count_values($fruits) i get Array ( => 4 => 3 [yellow] => 2 ) how can i asign the value of each key to a variable? i have the following array $fruits = array("cherry" => "red", "apple" => "red", "kiwi" => "green", "strawberry" => "red", "pear" => "yellow", "melon" => "green", "grapes" => "green", "watermelon" => "red", "banana" => "yellow") using the array_count_values($fruits) i get Array ( => 4 => 3 [yellow] => 2 ) how can i asign the value of each key to a variable? Ok, so first, I'm a little more experienced than a newb, but far from an expert. And I'm fairly certain when yall help me through this I'm going to bang my head on the desk and chastize myself for not thinking of it. So here we go. I'm attempting to use some examples I found on php.net for the iptc embed & iptcparse functions. What I've done is taken a class file that was posted (just a collection of the snippets), corrected it for the most part to function how it should. It will read the IPTC data from a jpg just fine. It'll even write to the IPTC fields. The problem comes with the IPTC_KEYWORDS field. That field needs to be an array and I can't get it to write properly. Right now the only thing it's writing is the word "array". Also, I'm a bit confused as to what one of the functions is trying to do and I think it's the function that's causing the mess. Below are the classfile and then the test file making the call. Code: [Select] <? /* Examples taken from php.net */ DEFINE('IPTC_OBJECT_NAME', '005'); DEFINE('IPTC_EDIT_STATUS', '007'); DEFINE('IPTC_PRIORITY', '010'); DEFINE('IPTC_CATEGORY', '015'); DEFINE('IPTC_SUPPLEMENTAL_CATEGORY', '020'); DEFINE('IPTC_FIXTURE_IDENTIFIER', '022'); DEFINE('IPTC_KEYWORDS', '025'); DEFINE('IPTC_RELEASE_DATE', '030'); DEFINE('IPTC_RELEASE_TIME', '035'); DEFINE('IPTC_SPECIAL_INSTRUCTIONS', '040'); DEFINE('IPTC_REFERENCE_SERVICE', '045'); DEFINE('IPTC_REFERENCE_DATE', '047'); DEFINE('IPTC_REFERENCE_NUMBER', '050'); DEFINE('IPTC_CREATED_DATE', '055'); DEFINE('IPTC_CREATED_TIME', '060'); DEFINE('IPTC_ORIGINATING_PROGRAM', '065'); DEFINE('IPTC_PROGRAM_VERSION', '070'); DEFINE('IPTC_OBJECT_CYCLE', '075'); DEFINE('IPTC_BYLINE', '080'); DEFINE('IPTC_BYLINE_TITLE', '085'); DEFINE('IPTC_CITY', '090'); DEFINE('IPTC_PROVINCE_STATE', '095'); DEFINE('IPTC_COUNTRY_CODE', '100'); DEFINE('IPTC_COUNTRY', '101'); DEFINE('IPTC_ORIGINAL_TRANSMISSION_REFERENCE', '103'); DEFINE('IPTC_HEADLINE', '105'); DEFINE('IPTC_CREDIT', '110'); DEFINE('IPTC_SOURCE', '115'); DEFINE('IPTC_COPYRIGHT_STRING', '116'); DEFINE('IPTC_CAPTION', '120'); DEFINE('IPTC_LOCAL_CAPTION', '121'); class iptc { var $meta=Array(); var $hasmeta=false; var $file=false; function iptc($filename) { echo 'IPTC Loading for: '.$filename.'<br />'; $size = getimagesize($filename,$info); $this->hasmeta = isset($info["APP13"]); if($this->hasmeta) $this->meta = iptcparse($info["APP13"]); $this->file = $filename; } function set($tag, $data) { echo 'Updating IPTC Tag.<br />'; $this->meta ["2#$tag"]= Array( $data ); $this->hasmeta=true; } function get($tag) { echo 'Getting IPTC data.<br />'; return isset($this->meta["2#$tag"]) ? $this->meta["2#$tag"][0] : false; } function view() { echo 'Print IPTC Data.<br />'; foreach(array_keys($this->meta) as $s) { $c = count ($this->meta[$s]); for ($i=0; $i <$c; $i++) { echo $s.' = '.$this->meta[$s][$i].'<br />'; } } } function binary() { echo 'Setting new binary block for IPTC writing.<br />'; $iptc_new = ''; foreach (array_keys($this->meta) as $s) { $c = count ($this->meta[$s]); for ($i=0; $i <$c; $i++) { $tag = str_replace("2#", "", $s); $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][$i]); } } return $iptc_new; } function iptc_maketag($rec,$dat,$val) { echo 'Making IPTC Tag<br />'; $len = strlen($val); if ($len < 0x8000) { return chr(0x1c).chr($rec).chr($dat). chr($len >> 8). chr($len & 0xff). $val; } else { return chr(0x1c).chr($rec).chr($dat). chr(0x80).chr(0x04). chr(($len >> 24) & 0xff). chr(($len >> 16) & 0xff). chr(($len >> 8 ) & 0xff). chr(($len ) & 0xff). $val; } } function write() { echo 'Writing file...<br />'; if(!function_exists('iptcembed')) return false; $mode = 0; $content = iptcembed($this->binary(), $this->file, $mode); $filename = $this->file; @unlink($filename); #delete if exists $fp = fopen($filename, "w"); fwrite($fp, $content); fclose($fp); } #requires GD library installed function removeAllTags() { 'Removing previous IPTC tags to re-write new data.<br />'; $this->hasmeta=false; $this->meta=Array(); $img = imagecreatefromstring(implode(file($this->file))); @unlink($this->file); #delete if exists imagejpeg($img,$this->file,100); } }; ?> And here's the test-call: Code: [Select] <?php require_once("iptceasy.php"); $i = new iptc("fortworden.jpg"); $keywords = array( "keywords" => "updatedkey1", "updatedkey2", "updatedkey3" , "updatedkey4" ); echo $i->set(IPTC_KEYWORDS, $keywords); $i->write(); echo 'Done.'; ?> If I try to set any of the other IPTC fields with a string, the functions work fine. I'm fairly certain the error is either in the set() function or the iptc_maketag() function. And the iptc_maketag() function is the one I'm stumped about. Is that binary that it's prepending to the data? Thanks for any light you can shed and help you can give on this in advance! -Mike I dont know how to word this really. what I want to do is Code: [Select] $Var[] = 3; $Var[] = 6; $Var[] = 2; $Var[] = 17; for($i=0; $i!=count($Var); $i++) { echo "#$i: ".$Var[$i]."\n"; } I know I might be able to use rand() but I need it to echo ALL of the variables in the array in a random order, I know if I use count to find out how many variables there are that it would echo them 4 times randomly but might echo the same variable 2 times making it to where it only echos 3 different varables, if I am being confusing please let me know, I just want to get this resolved, thanks! Hello, I am developing a PayPal IPN interface which works fine, all is passed for verification and comes back 'VALID'. After validation with PayPal I update a users subscription and do the rest I want to do, but there is one thing really really irritating me. It seems to be that this one particular table in the database does not want to accept anything I throw at it through PHP. Here's the code: Code: [Select] $query = "INSERT INTO `ipn_txn_logs` ( `date` , `payment_reason` , `pp_txn_id` , `pp_amount` , `pp_txn_charge` , `pp_txn_net_amount` , `ltj_txn_id` , `description` , `failsafe` , `member` ) VALUES ( '$date', 'subscribe', '$txn[txn_id]', '$txn[payment_amount]', '$txn[payment_charges]', '$txn[net_payment]', '$txn[custom]', '$desc', 'yes', '$fname $lname')"; $query = mysql_query($query); The array is set on the IPN return using all values from PayPal. The database will insert when all variable and arrays are left out of the INSERT and replaced with just the number 1.. I am unable to see a PHP error as it's done in the background after a PayPal response... is there anyway to collect this error? Also, any suggestions on this fault? George.[/code] Here's the code: Code: [Select] $year_values = array('Any', 'N/A', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012'); $db_year = explode(', ', $row['YEAR']); foreach($year_values as $year_value) { $selected_year = null; $year_label = $year_value; if(in_array($year_value, $db_year)) { $selected_year = ' checked="checked"'; $year_label = "<b>$year_value</b>"; } echo '<input type="checkbox" name="year" value="' . $year_value . '"' . $selected_year . ' />' . $year_label . ' '; } ?> [/code That pulls the data of the database and puts it in check boxes. The user can check/uncheck certain boxes but the problem is when it goes to the verify page it has only one value from the array that was selected. On the verify page it just checks if a box was checked and then implodes the array before submitting it into the database. [code] $year_s=implode($year,", "); So like I said there is only one value from the array when there should be as many as the user checks. So basically I believe the value isn't added to the array. hey guys im trying to result an array key and value if it has one...the code and results are below if anyone can help with this simple problem...thanks alot Code: [Select] <?php $columns = array('news_id' => 'id', 'news'); foreach ($columns as $column => $column_alias) { echo $column . ' ' . $column_alias; } ?> the result im getting is: news_id id 0 news but im just after the result of just result the column name and alias (if it has one) so im looking for the result news_id id news Hi there, im really stuck here. I have a table of records that are selected from my db and put into an array and randomly chooses them, outputting the results . Code: [Select] <?php $count = 0; while ($row = mysql_fetch_assoc($Ships4)){ $array[$count]['ShipID'] = $row['ShipID']; $array[$count]['ShipName'] = $row['ShipName']; $array[$count]['Dclass'] = $row['Dclass']; $count++; $total4 = count($array); $random4 = rand(0,$total4 - 1); $random_ship4 = $array[$random4]; $ShipID4 = $random_ship4['ShipID']; echo $ShipID4;} This all works fine, however I want to limit the number of random outputs from a number in a record in a different table. So i added: Code: [Select] <?php if ($count < $row_dclasscorella['Dclass4_totla']){ ?> the number from the field is 2. The trouble is that it doesnt take any notice and outputs the total number a random number for each record. It seems its not limiting it. How can i get this to work please??? Code: [Select] $count = 0; if ($count < $row_dclasscorella['Dclass4_totla']){ while ($row = mysql_fetch_assoc($Ships4)){ $array[$count]['ShipID'] = $row['ShipID']; $array[$count]['ShipName'] = $row['ShipName']; $array[$count]['Dclass'] = $row['Dclass']; $count++; $total4 = count($array); $random4 = rand(0,$total4 - 1); $random_ship4 = $array[$random4]; $ShipID4 = $random_ship4['ShipID']; echo $ShipID4;}}?> Thank You Hello, I am trying to get a list of elements from my Database and I need to save it in a JavaScript array. Here is what I've been trying to do. Code: [Select] mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error()); mysql_select_db($dbname) or die(mysql_error()); $query="SELECT idCountries, Country_Name FROM countries order by Country_Name "; $result = mysql_query ($query); $x=1; echo "<script type='text/javascript'>"; echo "var SelAry=[];"; echo "SelAry[0] = ['select', '0'];"; while($nt=mysql_fetch_array($result)) { echo "SelAry[$x]=['$nt[idCountries]', '$nt[Country_Name]']; "; $x++; } echo "</script>"; I am open to any suggestion. Thank you in advance. I am an ASP.NET developer and I have to call a soap methed written in PBP that takes an argument required an associative array such as $prices = array( 'Tires'=>'test1', 'Spark Plugs'=>'test2' ); can yoiu tell me what the internal representation is of the above Hi, I have a form that I want to allow users to be able to add specific links, some are set types (domains) and just require the iser to enter the link, however, one is for whatever they wish and they must enter a name to describe it. Now im going to enter it into a database with the following columns: USER_ID || LINK_URL || LINK_TYPE || LINK_NAME Link name is optional (only needed if the link type is their own custom one), the link types are ID's related to a table of link types (facebook, twitter etc). Now I'm assuming that to differentiate the form elements for insertion into the database I would need to have a hidden form element with the type ID inside? However I don't really know how to go on from here. A small version of the form would be <input type="text" name="facebook_link" /> <input type="hidden" name="facebook_id value="1" /> <input type="text" name="twitter_link" /> <input type="hidden" name="twitter_id value="2" /> <input type="text" name="own_site" /> <input type="text" name="own_site_description" /> <input type="hidden name="own_site_id" value="3" /> However, I'm assuming this is wrong because I'll need to enter everything into an array won't I? I just can't get my head round it to out put thi results into a foreach statement. Can anybody help me please? Here is how I get categories for article listing. Article can be written in several categories at once. So I have this code: Code: [Select] $category = '1,5,23,46'; //Category IDs $get_cats = explode("," , $category); $cats = ""; for ($i = 0; $i<count($get_cats); $i++ ) { $cat = trim($get_cats[$i]); $catSlug = get_value_of($cat, "inc/cat_ids.php"); $catName = str_replace("-"," ",$catSlug); $cats .= "<a href=\"index.php?category=$catSlug\">".strtoupper($catName)."</a>, "; } $cats = substr($cats,0,-2); As you can see there's get_value_of function that is used to read the category from the file. File is cat_ids.php and looks like this: Quote 1='category-name-1'; 2='category-name-2'; 3='category name-3'; 4='category-name-4'; 5='category-name-5'; etc. I want to improve this in order not to read the file at each step ("for" loop). Means, one can load the file and then generate a list of (links) category compared to the numbers (Ids). So if $category is "1,3,4" I want to get list like this (by reading cat_ids.php): category-name-1, category name-3, category-name-4 With current function I read value for every ID from file in every step. So if article have 10 or more categories script load file 10 or more times. Looking for a solution to do this from a reading file only once. Thanks. Hello =) I'm trying to create a javascript array which should be filled with data from a mysql database. so what i wannt to do is to loop out a new array element for each row in my database. I should also say that i'm working in a php file. I tried (and failed) to do it like this: Code: [Select] <?php include('databbaseconnect.php'); ?> <script type="text/javascript"> var StoreDetails = [ ['Please select an option','','','','',''], <?php mysql_select_db("alltomboule_se", $db); $result = mysql_query("SELECT * FROM spelare"); while($row = mysql_fetch_array($result)) { echo "['".$row['namn'].$row['enamn']."','".$row['namn'].",'".$row['enamn']."','".$row['klubb']."','".$row['licensnr']."','".$row['id']."'],"; } ?> ['','','','','',''] // Note: no comma for last row ]; I wannt the array to look like this: Code: [Select] var StoreDetails = [ ['Please select an option','','','','',''], ['Oscar Andersson','Oscar','Andersson','BON','16643','2'], ['Olle Johansson','Olle','Johansson','BFT','14443','3'], ['Ingvar Andersson','Ingvar','Andersson','BON','14333','4'], ['Kalle Kula','Kalle','Kula','BON','34576','5'], ['','','','','',''] ]; I WANT HELP WITH ASSOCIATIVE ARRAY THERE IS ARRAY LIKE THIS $ARRAY= array( 'dd'=>1, 'dde'=>233, 'qww'=2231 ) i want to store this array in database which data type i should i use want to use mixed data mixed string-numeric type which data type is suitable and i want to print indexes only but values only what should i do I know you can use str_replace to replace a value with another value, or an array of values with an array of other values. What I'd like to do is replace each instance of a single value with an array of values which get iterated through for each instance found. Think prepared statements that you don't have to call setString or setInt on. Here's a made up example. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = ? AND user_role = ?; $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I have everything else working except this. It works if I specify an array of values to replace and do something like below, but I was hoping to not have to support that method of replace if I didn't need to. Code: [Select] $db->query = 'SELECT * FROM users WHERE user_name = :name AND user_role = :role; $db->replace = array(':name',':role'); $db->params = array('hopelessX','admin'); $db->executeQuery(); //this contains a call to a private function that does the replace I can do it that way if I need to or I could make some overly complicated thing that finds each instance of the question mark, replaces it with a unique value and then adds that unique value to a replace array similarly to the method in code block two but that defeats to the purpose of making this simple database adapter in the first place (although it was mostly just for fun anyway). Anyway, if anyone has any advice and knows of a simple means to achieve this goal that would be much appreciated. Thanks in advance Hello dear friends, hello community, i want to parse a site http://www.aktive-buergerschaft.de/buergerstiftungsfinder Well therefore i have a true beginner-question regarding Array in order to work with the data: beginner question The results should be stored in a MySQL-Database: well you see. i have a Curl-Approach: and i want to work with the parsed data: and in this case i want to give over the data into an array (if viewing the output in web browser, do view-source to see structured array). Here the musings that led to the code: Depending on num dimensions, we could do, foreach($result as $k => $v) {echo $k." ".$v} to view and work with data (adding sub foreach loops accordingly; i.e. if $v is itself an array) see the results: What do you think: Code: [Select] $ch = curl_init("http://www.aktive-buergerschaft.de/buergerstiftungsfinder"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $buffer = curl_exec($ch); curl_close($ch); $result = explode(",", $buffer); foreach($result as $k => $v) {echo $k." ".$v} if $v is itself an array) // print_r($result); look forward to hear from you!! db1 Hi, In my mysql database i have a text input option, in the registration form and edit my details form i have a multiple select dropdown list, which user selects options to populate the text input box, which ultimately populates the text field in the mysql database. All works perfectly. The dropdownlist consists of 3 parts <optgroups> first is current selection (what is the usesr current selection)works fine, The second <optgroup> is existing words, what words we(the site) have given as options, and the third <optgroup> is the words that others have used. This is where im having a small problem. Because its a text field when i call the data from the database, it calls the entire text box as a single option in my select list.. I want to break the words in the text field (at the comma) and have them listed each one as an option in the select list. Example what i need: Words in text box:(my input allows the "comma") word1, word2, word3, word4, word5, word6, How i want them called/displayed: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> here's my code: $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $original_functionsexperience =doSelectSql($query,1); $query = "SELECT allwords FROM #__functions_experience WHERE profile_id = '".(int)$profileId."' LIMIT 1"; $functionsexperiencelist=doSelectSql($query); $funcexpList ="<select multiple=\"multiple\" onchange=\"setFunctionsexperience(this.options)\">"; foreach ($functionsexperiencelist as $functionsexperienceal) { $selected=""; if ($functionsexperienceals->allwords == $original_functionsexperience) $selected=' selected="selected"'; $allwords=$functionsexperienceal->allwords; $funcexpList .= "<optgroup label=\"Current selection\"> <option value=\"".$allwords."\" ".$selected." >".$allwords."</option> </optgroup> <optgroup label=\"Existing Words\"> <option value=\"existing1,\">existing1</option> <option value=\"existing2,\">existing2</option> <option value=\"existing3,\">existing3</option> <option value=\"existing4,\">existing4</option> <option value=\"existing5,\">existing5</option> <option value=\"existing6,\">existing6</option> </optgroup> <optgroup label=\"Others added\"> //heres problem <option value=\"".$allwordsgeneral."\">".$allwordsgeneral."</option> </optgroup>"; } $funcexpList.="</select>"; $output['FUNCEXPLIST']=$funcexpList; The result im getting for optgroup others added: word1, word2, word3, word4, word5, how can i get it like this: <option value=\"word1\">word1</option> <option value=\"word2\">word2</option> <option value=\"word3\">word3</option> <option value=\"word4\">word4</option> <option value=\"word5\">word5</option> <option value=\"word6\">word6</option> Code: [Select] require('../conn/db_connection.php'); //seleksi restoran $pilih_resto="select * from restoran"; $query_pilih_resto=mysql_query($pilih_resto); echo "<h3>Truly Data : </h3>"; while($resto=mysql_fetch_array($query_pilih_resto)){ echo"<font color='red'>".$resto["id_restoran"].".". $resto["nama_restoran"]."</font><br>"; $seleksi_menu_1="select * from jenis_menu"; $query_menu_1=mysql_query($seleksi_menu_1); while($menu_1=mysql_fetch_array($query_menu_1)){ echo "<font color='green'>".$menu_1["id_jenis_menu"]."</font><br>"; $seleksi_data_eat="select * from eat where id_restoran like '".$resto["id_restoran"]."' and id_jenis_menu like '".$menu_1["id_jenis_menu"]."'"; $query_eat=mysql_query($seleksi_data_eat); while($eat=mysql_fetch_array($query_eat)){ echo $eat["nama_eat"]."<br>"; } } echo"<br>"; } echo "------------------------------<br>"; echo "<h3>Random Data : </h3>"; $pilih_resto_2="select * from restoran"; $query_pilih_resto_2=mysql_query($pilih_resto_2); $menu_PNP="PNP"; $menu_PBK="PBK"; $menu_UTM_1="UTM"; while($data_resto=mysql_fetch_array($query_pilih_resto_2)){ echo "<b>".$data_resto["id_restoran"]."-".$data_resto["nama_restoran"]."</b><br>"; $seleksi_data_eat_PNP="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_PNP."'"; $seleksi_data_eat_PBK="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_PBK."'"; $seleksi_data_eat_UTM="select * from eat where id_restoran like '".$data_resto["id_restoran"]."' and id_jenis_menu like '".$menu_UTM_1."'"; $query_eat_UTM=mysql_query($seleksi_data_eat_UTM); $jml_data_UTM=mysql_num_rows($query_eat_UTM); echo "Summary of main Menu : $jml_data_UTM<br>"; $query_eat_PNP=mysql_query($seleksi_data_eat_PNP); $query_eat_PBK=mysql_query($seleksi_data_eat_PBK); while($eat_PNP=mysql_fetch_array($query_eat_PNP)){ $data_eat_PNP[]=$eat_PNP["nama_eat"]; } while(list($index_PNP,$data_PNP)=each($data_eat_PNP)){ $data_eat_PNP_list[$index_PNP]=$data_PNP; } while($eat_PBK=mysql_fetch_array($query_eat_PBK)){ $data_eat_PBK[]=$eat_PBK["nama_eat"]; } while(list($index_PBK,$data_PBK)=each($data_eat_PBK)){ $data_eat_PBK_list[$index_PBK]=$data_PBK; } while($eat_UTM=mysql_fetch_array($query_eat_UTM)){ $eat_UTMx[]=$eat_UTM["nama_eat"]; } for($i=0;$i<$jml_data_UTM;$i++){ $random_data_PNP[$i]=array_rand($data_eat_PNP_list,1); $random_data_PBK[$i]=array_rand($data_eat_PBK_list,1); echo "<font color='red'>".$data_eat_PNP_list[$random_data_PNP[$i]]."</font>---<font color='green'>". $eat_UTMx[$i]."</font>---<font color='blue'>".$data_eat_PBK_list[$random_data_PBK[$i]]."</font><br>"; } } Please Help, There is a random error data how to create random data like this? Data => Restoran A: Menu appetizers : - Sup - Sate Usus - Trancam Main Menu - Nasi Goreng - Nasi Goreng Putih - Nasi + Ayam Penyet - Nasi + Bebek Panggang - Ikan Gurame Asam + Nasi - Nasi Soto Menu Dessert - Pudding - Buah Segar - Juice Aplukat Restoran B : Menu appetizers -Sup Ikan Paprika -Sup Jamur Spesial -Sup Urat Sapi Saus Tiram -Sup May Jala - Jala Main Menu - Bubur Ayam Kombinasi - Bubur Ayam/Sapi Clay Pot - Bubur Telor Pitan Clay Pot - Gurame Panggang - Pangsit Udang - Cumi-cumi Goreng Special - Kepiting Lembek Mentega - Sayap Ayam Panggang Dessert -Juice Alpukat -Mix Juice -Sui Kiau Goreng Salad -Ha Kaou Sayuran Out Put : Restoran A : Menu e ---+--- Main Menu --+---- Dessert ---------------------------------------------------- Sup ------- Nasi Goreng ------- Pudding Sup ------- Nasi Goreng Putih ------- Juice Aplukat Sate Usus ------- Nasi + Ayam Penyet ------- Pudding Sup ------- Nasi + Bebek Panggang ------- Buah Segar Trancam ------- Ikan Gurame Asam + Nasi ------- Buah Segar Sate Usus ------- Nasi Soto ------- Pudding Restoran B : Menu Pembuka ---+-- Menu Utama --+--- Menu Penutup ----------------------------------------------------------------------- Sup Ikan Paprika ------- Bubur Ayam Kombinasi ------- Juice Alpukat Sup Urat Sapi Saus Tiram ------- Bubur Ayam/Sapi Clay Pot ------- Sui Kiau Goreng Salad Sup May Jala-Jala ------- Bubur Telor Pitan Clay Pot ------- Juice Alpukat Kepiting Lembek Mentega ------- Gurame Panggang ------- Juice Alpukat Sup Urat Sapi Saus Tiram ------- Pangsit Udang ------- Mix Juice Sup May Jala-Jala ------- Cumi-cumi Goreng Special ------- Ha Kaou Sayuran Sup Jamur Spesial ------- Kepiting Lembek Mentega ------- Sui Kiau Goreng Salad Sup May Jala-Jala ------- Sayap Ayam Panggang ------- Ha Kaou Sayuran Note : appetizers and desserts at random based on count of data main menu Hi, i'm getting an error when I load my php code in a browser. Here's my code snippet: <?php mysql_connect("localhost","root"); mysql_select_db("something"); $bellProductsArray=array(1=>"Apple_iPhone3GS.jpg",2=>"Apple_iPhone4.jpg"); $result=mysql_query("SELECT Name, Manufacturer FROM bellProducts WHERE ID=1"); $row=mysql_fetch_assoc($result); print "Name: {$row['Name']} Manufacturer: {$row['Manufacturer'] }"; ?> <img src=<?php array_values($bellProductsArray); ?> alt="Apple iPhone 3GS" title="Apple iPhone 3GS" /> **I can't get it to display the first image (eg: Apple_iPhone3GS.jpg), I made sure that I have the image in same directory. please help!1! I'm trying to learn arrays and I have this problem: I have a variable $a which is a result from a from a database query If I echo it I get: Code: [Select] forenamesurnamedate_of_birthgenderpaypal_addresspayment_planaddress_line_1address_line_2address_cityaddress_zip_post_codeaddress_countrytelephonemobilewhere_did_you_hearreceive_newsletter If I var_dump($a) I get: Code: [Select] string(8) "forename" string(7) "surname" string(13) "date_of_birth" string(6) "gender" string(14) "paypal_address" string(12) "payment_plan" string(14) "address_line_1" string(14) "address_line_2" string(12) "address_city" string(21) "address_zip_post_code" string(15) "address_country" string(9) "telephone" string(6) "mobile" string(18) "where_did_you_hear" string(18) "receive_newsletter" My question is, how do I get each value from a? It looks like an array to me because it holds multiple strings. I need to get the first, second and third elements printed on the page and used in other areas of my program. Thanks in advance Hi I found a tutorial on dealing with databases he http://www.phpfreaks.com/tutorial/php-basic-database-handling It's great, except that I need it to do more than just a name; I need first, last, dob and email. I have it figured out how to order, insert and delete, but can someone help me figure out how to do the updating? The tutorial creates an array called cname and loops through it to do the update, but when I add more fields, it only holds the last fileds (emails in this case) I just need to be able to update all the fields for each user instead of just the name. Sounds easy but I've gotten nowhere Everything I have tried is posted below. Any help? Thanks Code: [Select] // INSERT: if we have a name to add... if($_POST['fname']) { // little bit of cleaning... $fname = mysql_real_escape_string($_POST['fname']); $lname = mysql_real_escape_string($_POST['lname']); $dob = mysql_real_escape_string($_POST['dob']); $email = mysql_real_escape_string($_POST['email']); // check for previous entry $sql_check = "SELECT id FROM test WHERE fname='$fname' AND lname='$lname'"; $res_check = mysql_query($sql_check, $conn) or trigger_error("SQL", E_USER_ERROR); if (mysql_num_rows($res_check) == 1) { while ($row = mysql_fetch_assoc($res_check)) { $id = $row['id']; } // update $sql = "UPDATE test SET Current=1 WHERE id='$id'"; $res = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } else { // insert new name into table $sql = "INSERT INTO test (id, fname, lname, dob, email) VALUES ('', '$fname', '$lname', '$dob', '$email')"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } } // end if // UPDATE: if we have name(s) to change... if($_POST['udata']) { /* // for each name to change... foreach ($_POST['udata'] as $input => $v) { echo "$input = $v<br />"; $sql = "UPDATE test SET "; foreach ($v as $id => $value) { echo "$id = $value<br />"; } $sql .= "WHERE ..."; } echo "<hr />$sql<hr />"; print_r($_POST['udata']); */ for ($i = 0; $i < count($_POST['udata']['fname']); $i++) { $fname = $_POST['udata']['fname'][$i]; echo "$i = $fname<br />"; } /* foreach($_POST['cname'] as $cid => $cname) { // little bit of cleaning... $id = mysql_real_escape_string($cid); $fname = mysql_real_escape_string($cname); $lname = mysql_real_escape_string($cname); $dob = mysql_real_escape_string($cname); $email = mysql_real_escape_string($cname); // update name in the table $sql = "UPDATE test SET fname = '$fname', lname='$lname', dob='$dob', email='$email' WHERE id = '$id'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } // end foreach */ } // end if // DELETE: if we have a name to delete... if($_GET['id']) { // little bit of cleaning... $id = mysql_real_escape_string($_GET['id']); // delete name from table $sql = "UPDATE test SET Current=0 WHERE id= '$id'"; $result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); } // end if // ORDERBY: if one of the links was clicked.. if ($_GET['orderby']) { // make an aray of allowed names $allowed = array('id','fname', 'lname', 'dob', 'email'); // bit of cleaning... $order = mysql_real_escape_string($_GET['orderby']); // is it a valid column name? yes: use it. no: default to 'id' $order = (in_array($order, $allowed))? $order : "id"; // if no link clicked, default to 'id' } else { $order = "id"; } // end else // SELECT: get the list of names from database $sql = "SELECT id, fname, lname, dob, email FROM test WHERE Current=1 ORDER BY $order"; //$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR); $result = mysql_query($sql, $conn) or die(mysql_error()); /**** end deal with the database ****/ /**** list everything out ****/ // list columns echo "<form action = '{$_SERVER['PHP_SELF']}' method = 'post'>\r\n"; echo "<table border = '1'>\r\n"; echo "<tr>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=id'>id</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=fname'>fname</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=lname'>lname</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=dob'>dob</a></td>\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?orderby=email'>email</a></td>\r\n"; echo "<td>delete</td>\r\n"; echo "</tr>\r\n"; // loop through list of names while ($list = mysql_fetch_assoc($result)) { echo "<tr>\r\n"; echo "<td>{$list['id']}</td>\r\n"; echo "<td><input type = 'text' name = 'udata[fname][{$list['id']}]' value = '{$list['fname']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[lname][{$list['id']}]' value = '{$list['lname']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[dob][{$list['id']}]' value = '{$list['dob']}' />\r\n"; echo "<td><input type = 'text' name = 'udata[email][{$list['id']}]' value = '{$list['email']}' />\r\n"; echo "<td><a href = '{$_SERVER['PHP_SELF']}?id={$list['id']}'>delete</a></td>\r\n"; echo "</tr>\r\n"; } // end while // list input box for adding new entry echo "<tr>"; echo "<td bgcolor = 'gray'></td>\r\n"; echo "<td><input type = 'text' name = 'fname' /></td>\r\n"; echo "<td><input type = 'text' name = 'lname' /></td>\r\n"; echo "<td><input type = 'text' name = 'dob' /></td>\r\n"; echo "<td><input type = 'text' name = 'email' /></td>\r\n"; echo "<td bgcolor = 'gray'></td>\r\n"; echo "</tr><tr>\r\n"; echo "<td></td>\r\n"; echo "<td align = 'center'><input type = 'submit' value = 'submit' /></td>\r\n"; echo "<td></td>\r\n"; echo "</tr></table></form>\r\n"; /**** end list everything out ****/ Say i have an array (called $myarray) and it has 10 numbers in it like this... 1 2 4 8 9 10 12 14 15 18 Now in my code, I get a number and lets say for this example it is "5". I need to see if that number is in the array --easy enough using in_array()--, but if it is NOT in the array, I need to find the next available number in the array that is greater than my starting number of 5 (which would be "8" in this example). But what is the best way to find this number (i.e. 8 in this example)? I imagine I need to somehow loop through but i'm not sure which loop is the best to use and i'm generally confusing the hell out of myself (which is frustrating because this is probably rather simple to do ). Can anyone help guide me in the right direction? i have an array in the loop but it isn't building up with results. i want it to check if the array exists, if not then create the array. Then in next loop it pushes a new value into the array. Below isn't working?... Code: [Select] while($row=mysql_fetch_assoc($get)); { $key = $row['keyword']; $scope= $_SESSION['scope']; if (!is_array($scope)) { $scopenew = array($key); $_SESSION['scope'] = $scopenew; } else { $scopenew = array_push($scope, $key); $_SESSION['scope'] = $scopenew; } } Hi All I'm new to php and I have a multidimensional array set up which I need to sort for a results list from an assessment. The array is $gradout['name']['userid']=score. I need to sort the array by score in a decending order. ['name'] is a string and ['userid'] is a numeric. I've tried looking at the php manual but It's just confusing me. Can anyone explain to me in laymans terms what I need to do and why. Hi, Ihave the below array output from a DB query. I need to convert into the bottom array for Google CHarts. Any ideas? $myarray = array( 0 => array( 'year' => 2009, 'month' => "January", 'month_sales' => 524, 'year_totalsales' => 3610 ), 1 => array ( 'year' => 2009, 'month' => 'February', 'month_sales' => 521, 'year_totalsales' => 3610 ), 2 => array ( 'year' => 2009, 'month' => 'March', 'month_sales' => 501, 'year_totalsales' => 3610 ), 3 => array ( 'year' => 2009, 'month' => 'April', 'month_sales' => 601, 'year_totalsales' => 3610 ), 4 => array ( 'year' => 2009, 'month' => 'May', 'month_sales' => 710, 'year_totalsales' => 3610 ), 5 => array ( 'year' => 2009, 'month' => 'June', 'month_sales' => 801, 'year_totalsales' => 3610 ), 6 => array ( 'year' => 2009, 'month' => 'July', 'month_sales' => 991, 'year_totalsales' => 3610 ), 7 => array ( 'year' => 2009, 'month' => 'August', 'month_sales' => 301, 'year_totalsales' => 3610 ), 8 => array ( 'year' => 2009, 'month' => 'September', 'month_sales' => 250, 'year_totalsales' => 3610 ), 9 => array ( 'year' => 2009, 'month' => 'October', 'month_sales' => 322, 'year_totalsales' => 3610 ), 10 => array ( 'year' => 2009, 'month' => 'November', 'month_sales' => 621, 'year_totalsales' => 3610 ), 11 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 691, 'year_totalsales' => 3610 ), 12 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 789, 'year_totalsales' => 1610 ), 13 => array ( 'year' => 2010, 'month' => "February", 'month_sales' => 1409, 'year_totalsales' => 1610 ), 14 => array ( 'year' => 2010, 'month' => "March", 'month_sales' => 550, 'year_totalsales' => 1610 ) ); raw_data=[['January',524,0],['February',521,0],['March',501,0],['April',601,0],['May',710,0],['June',801,0], ['July',991,0],['August',301,0],['September',250,0],['October',322,0],['November',621,0],['December',691,0],['January',789,0],['February',1409,0],['March',550,0],]; raw_data= [ [ month1 , year1 sales figure(zero if no figure), year2 sales figure(zero if no figure).....], [ month1 , year1 sales figure(zero if no figure), year2 sales figure(zero if no figure).....]......]; Thanks all Hi, I have the following code so far : Code: [Select] <? $myarray = array( 0 => array( 'year' => 2009, 'month' => "November", 'month_sales' => 524, 'year_totalsales' => 3610 ), 1 => array ( 'year' => 2009, 'month' => 'December', 'month_sales' => 521, 'year_totalsales' => 3610 ), 2 => array ( 'year' => 2010, 'month' => "January", 'month_sales' => 609, 'year_totalsales' => 3610 )); $lastyear = ""; echo "<table><tr><th>Month</th><th>Sales</th></tr>", PHP_EOL; foreach($myarray as $row) { if ($row['year'] != $lastyear) { echo "<tr><th colspan=2>", $row['year'], "</th></tr>", PHP_EOL; $lastyear = $row['year']; } echo "<tr><td>", $row['month'], "</td><td>", $row['month_sales'], "</td></tr>", PHP_EOL; } echo "</table>", PHP_EOL; ?> BUt this code gives me this: Code: [Select] <table><tr><th>Month</th><th>Sales</th></tr> <tr><th colspan=2>2009</th></tr> <tr><td>November</td><td>524</td></tr> <tr><td>December</td><td>521</td></tr> <tr><th colspan=2>2010</th></tr> <tr><td>January</td><td>609</td></tr> </table> Instead of this: Code: [Select] <table><tr><th>Month</th><th>Sales</th></tr> <tr><th colspan=2>2009</th></tr> <tr><td>November</td><td>524</td></tr> <tr><td>December</td><td>521</td></tr> </table> <table><tr><th>Month</th><th>Sales</th></tr> <tr><th colspan=2>2010</th></tr> <tr><td>January</td><td>609</td></tr> </table> ANy help appreciated thanks Hi, Need help in parsing the . I am new to php and need to parsing and print only few elements in the arrary I have an array as below: Array ( [@attributes] => Array ( [WARRANTYCATEGORY] => Customer Warranty [NA_RATING] => [TAGCATEGORY1] => [TAGCATEGORY1DESC] => [TAGCATEGORY2] => [RESPONSEDATE] => 08-14-2006 04:40:40 PM [CASEID] => 1435435 [DUTYMANAGERAPPROVALTEXT] => [COUNTER] => 0 [DESCRIPTION] => SPRLSL:Cluster Notification [NA_BUGNO] => [PRIORITY] => 3 [WARRANTYPRODUCT] => WARR36MTH_HW_DISK [NA_DISRUPTION_EVENT] => [SERIALNUMBER] => 123456789 [NADUPCASEID] => [DMGERAPPRL] => [SYSNAME] => REWSRAPP34 [DATECLOSED] => 08-17-2006 04:47:37 PM [CASE_STATUSTEXT] => Closed [NASUPPORTOFFERING] => ST [CREATEDBY] => ) ) I need to access only CASEI D, CASE_STATUSTEXT and DATECLOSED from the above array How can I access that ? Thanks and Regards, Usha I have a file that contains, among others, some links to other files. Those files contain links to other files and so on. What I want to do is to check if a file has already been opened, and if this is true I want the file not to be opened again. For this I created an array, but when the code returns to the first file the array is reseted. Can someone please help me? This is the code I created (I`m a beginer in php). Thanks function readImportFiles($taxonomyFile, $target_path, $fileName='', $ArrayOfTaxonomies = array()) { while(!feof($taxonomyFile)) { $line = fgets($taxonomyFile); //code for getting the $schemaLocation if ($schemaLocation && !in_array($schemaLocation, $ArrayOfTaxonomies)) { $ArrayOfTaxonomies[]= $schemaLocation; $importSchema = fopen($schemaLocation, "r"); $target_path = substr($schemaLocation, 0, (strlen($schemaLocation) - strlen(strrchr($schemaLocation, "/")))); readImportFiles($importSchema, $target_path, $schemaLocation, $ArrayOfTaxonomies); } } } How can I merge the array, but I keep in mind that I only need to merge userlocation and the usercity arrays. Current output... Code: [Select] Array ( [0] => Array ( [0] => userlocation [1] => 19 ) [1] => Array ( [0] => credentials [1] => ) [2] => Array ( [0] => specialties [1] => ) [3] => Array ( [0] => usercity [1] => place1 ) ) Desired output... Code: [Select] Array ( [0] => Array ( [0] => userlocation [1] => 19 [2] => usercity [3] => place1 ) [1] => Array ( [0] => credentials [1] => ) [2] => Array ( [0] => specialties [1] => ) ) How can this be done? The array is dynamic. What is the point of serializing an array and can some show me an example as to when it should be used? Hi guys, I'm really struggling trying toremove duplicates from an associative array. I've tried array_unique but it doesn't work. Can you point me in the right direction please? I'm populating my array using the following code Code: [Select] foreach($category['manufacturers'] as $manufacturer) { list($name, $id) = explode("|", $manufacturer); $brands[] = array("id" => $id, "name" => $name); } If the array contains: id = 1, name = brandA id = 2, name = brandB id = 1, name = brandA I'd like to remove either the first or third entry. I always struggle with associative arrays Hi everybody, im reading up on arrays and im still stuck... Is it possible to assign an array to a variable? I need something like... Code: [Select] &needvariable = $row->User Hopefully this makes sense... I am reading hundreds of CSVs to import into a DB. Some of the column names contain the same data but have different names across all the files. For example, one file will say Phone where the other says EveningPhone...both contain the same data, different names. I am trying to rename everything to EveningPhone because I had most of the code done when i realized there were different header names in different files. Too lazy to replace all i guess.. I am creating an assoc array to match the data then off to the db it goes.. The problem is I cannot get the keys to rename to one convention. Here is the function where it happens: Code: [Select] public function readCSV($file) { /** * @todo: LOAD THE FILE INTO A MULTIDIMENSIONAL ASSOCIATIVE ARRAY TO DETERMINE THE FILEDS */ // Read the first line to get the headers $headers = fgetcsv($file); if (!array_key_exists('EveningPhone', $headers)) { if (array_key_exists('Phone', $headers)) { $headers['EveningPhone'] = $headers['Phone']; unset($headers['Phone']); } else { die("other"); } } format::neat_r($headers); // basically print_r but adds a new line to read it easier... die(); At the end, I still get EveningPhone not defined errors from a file that uses Phone as the phone number.. Anybody have any ideas? hello.... I'm stuck... I'm trying to populate a check box with a 2d array. I have made three arrays within one array, but when i run it, nothing appears.. here is the code i have used so far: Code: [Select] <legend>Optional extras</legend> <optgroup label="Entertainment"> <?php foreach($car_extras as $car_extras_id => $extras) { echo '.$car_extras_id.'; { foreach($extras as $entertainment) $i++; echo '<input type=checkbox name="options" value="'.$extras.'" id="entertainment'.$num[$i].'"/>'; echo '<label for ="entertainment'.$num[$i].'">'.$entertainment.'</label><br/>'; } } ?> This is the array code Code: [Select] $car_extras = array ("Entertainment"=>array("6 disc DVD changer", "TV function", "DAB digital radio", "Loudspeaker system - professional", "Multimedia navigation system"), "Communication"=>array("Universal remote control", "Voice control", "Navigation system","Head-up display"), "Safety & Security"=>array("Adaptive headlights", "Night vision with pedestrian recognition", "Run-flat tyres")); Thanks for the help! I looked through all the array functions in the manual, but didn't see what I needed (might have just missed it) Is there a way to stick a value into the middle of an array, without writing over the current value? I would need it to just push the rest back 1. Hope that explains what Im looking for! Thanks in advance I have the current data show up when I do a var_dump. Code: [Select] Code $result = $wrap->get_lists(); echo "Result of lists:<br />"; if($result->was_successful()) { echo "Got lists\n<br /><pre>"; var_dump($result->response); //print_r($result->response); } else { echo 'Failed with code '.$result->http_status_code."\n<br /><pre>"; var_dump($result->response); } echo '</pre>'; Data Output array(303) { [0]=> object(stdClass)#5 (2) { ["ListID"]=> string(32) "df2d1497b0f4bdc3b8b77863f6721025" ["Name"]=> string(14) "DATA1" } [1]=> object(stdClass)#6 (2) { ["ListID"]=> string(32) "f44d9acf655e914b944d7174bdd521ff" ["Name"]=> string(14) "DATA2" } [2]=> object(stdClass)#7 (2) { ["ListID"]=> string(32) "c84f4ba6b86bc508e6922f4ca44ab41c" ["Name"]=> string(14) "DATA3" } [3]=> object(stdClass)#8 (2) { ["ListID"]=> string(32) "b7dc652cd5060194362f19667ddf47e9" ["Name"]=> string(14) "DATA4" } } What I need to achieve is get the data in "ListID" out so I can run "ListID" through another function of mine, to delete records. Any ideas, how I would get "ListID" values out of the array? Code: [Select] elseif(isset($_GET['search'])){ $search=$_POST['search']; $search=str_replace(" ", "+", $search); header("Location: ./index.php?q=".$search); } elseif(isset($_GET['q'])){ $search=$_GET['q']; $keywords=explode("+",$search); $sql10000="SELECT product_id FROM $tbl_name2 WHERE "; while($query10000=each($keywords)){ $sql10000.="keyword LIKE '%".$query10000."%' OR"; } $sql10000=substr($sql10000,0,(strLen($sql10000)-3)); $content=$sql10000; That is returning this: SELECT product_id FROM keywords WHERE keyword LIKE %Array% For some reason it's showing "Array", it should be looping through the keywords array. i have a form with multiple checkboxes, with the same name. so i put them in an array like this. Code: [Select] <input type='checkbox' name='test[]' value='' /> <input type='checkbox' name='test[]' value='' /> <input type='checkbox' name='test[]' value='' /> <input type='checkbox' name='test[]' value='' /> Now when i do print_r($_POST['test']; , it should display an array and if each checkbox has been ticked or not. it just comes up blank. Any idea? Hi Guys, I'm trying the following.. returning an array from a php function to Ajax success but the alert seems to only display undefined. PHP Code: [Select] public function reply() { $item_id = $this->uri->segment(3); $type = $this->uri->segment(4); if($type == 1){ $data['get_news_item'] = $this->Newsletter_model->get_news_item($item_id); $test = array( "Paul", "Mike"); return $test; } } AJAX Code: [Select] $.ajax({ type: "POST", url: "<?php echo site_url(); ?>newsletter/reply/"+id+"/"+type, cache: false, success: function (data){ alert(data[0]); // So this should display "Paul"? }); [/code] 'm trying to write a script that will covert an XML response to an Array. The format of the xml response is the following (1 of 2 possibilities): Code: [Select] if found <response> <imei>123123123123111</imei> <unlockcode>34343434</unlockcode> </response> if not found: <response> <imei>123123123123111</imei> <unlockcode>Not Found</unlockcode> </response> I've been able to create the xml files yes.xml and no.xml and using this script I found on the internet have been able to parse it. Code: [Select] <?php function objectsIntoArray($arrObjData, $arrSkipIndices = array()) { $arrData = array(); // if input is object, convert into array if (is_object($arrObjData)) { $arrObjData = get_object_vars($arrObjData); } if (is_array($arrObjData)) { foreach ($arrObjData as $index => $value) { if (is_object($value) || is_array($value)) { $value = objectsIntoArray($value, $arrSkipIndices); // recursive call } if (in_array($index, $arrSkipIndices)) { continue; } $arrData[$index] = $value; } } return $arrData; } $xmlUrl = "no.xml"; // XML feed file/URL $xmlStr = file_get_contents($xmlUrl); $xmlObj = simplexml_load_string($xmlStr); $arrXml = objectsIntoArray($xmlObj); // print_r($arrXml); // print $arrXml['unlockcode']; if ($arrXml['unlockcode'] == "Not Found") { echo "Unable to find the unlock code"; } else { echo "Found the code! Here it is!"; echo $arrXml['unlockcode']; } ?> What I'm trying to do is create a file response.php that will parse the information sent from the server in the xml format described above into an array (instead of reading it from a local file). Your help is appreciated! Thanks in advance. |