PHP - Associative Array Values As Keys For Associate Array
Hi there,
Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. Similar TutorialsHello I have been taking a look at associative arrays. I 'sort' of get the key/value idea, but I'm not quite sure if they appropriate for use with 3 items (as opposed to the 2 key/value items.) In the code below, I can incorporate the 'company' and 'table' values - but I'm not sure how to add the 'id' value (from the query). I would very much appreciate some guidance here. Thank you. Code: [Select] $a = array(); // 'A' table array $b = array(); // 'B' table array $c = array(); // 'C' table array $query = "SELECT id, company, `table` FROM EXHIBITORS WHERE year = $year ORDER BY company ASC"; $result = mysql_query($query) or die("There was a problem with the SQL query: " . mysql_error()); if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $testCol = substr($row['table'], 0, 1); if ($testCol == 'A') { $a[$row['company']] = $row['table']; } else if ($testCol == 'B') { $b[$row['company']] = $row['table']; } else if ($testCol == 'C') { $c[$row['company']] = $row['table']; } } echo "<table>"; foreach($a as $key => $value){ echo "<tr><td>company: $key</td><td>Table: $value </td></tr>"; } echo "</table>"; echo "<table>"; foreach($b as $key => $value){ echo "<tr><td>company: $key</td><td'>Table: $value </td></tr>"; } echo "</table>"; echo "<table>"; foreach($c as $key => $value){ echo "<tr>"<td>company: $key</td><td>Table: $value </td></tr>"; } echo "</table>"; } else { echo "No Exhibitor data for the year $_POST[selectByYear]"; } 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 I need some help converting my captured array values into keys and later add arrays as the values. This might help explain what I'm looking for: I currently have Code: [Select] Array ( [0] => Meat [1] => Veg ) But I'm after Code: [Select] Array ( Meat => Veg => ) My end result will be: Code: [Select] [Veg] => Array ( [Potatoe] => 12 [Cabbage] => 24 [Cucumber] => 56 ) [Meat] => Array ( [Chicken] => 23 [Beef] => 90 ) I think either array_values() may help but I'm not too sure how to use it. What I'm trying to do is take two arrays and combine them using array_combine. After they are combined I want to take each key and value pair and use them in a string to build a MySQL query. See below for some pseudo-code =D <?php $fields = array('first_name', 'last_name'); //the fields that will be set with an UPDATE query. $newvals = array('Joe', 'Blow');//The values that will go into $fields $arr = array_combine($fields, $newvals);//Each value now has a key of the field it will update. /** This is where I want to return my SET string with something like 'SET ' . $arr['first_name'] ' = ' . $arr['first_name_value'] ', etc etc. */ There it is, I suppose. Are there any easier ways of doing what I'm trying to accomplish, that is, am I on the right track or just making things harder for myself? Both arrays will have dynamic values throughout my application, so I need to be able to get both each field and value for each query. Any links to some constructs, etc, etc? That's all I really need and I can post the solution when I've figured it out. Say I have this array: Code: [Select] <?php $array = array('one' => array(), 'two' => array(), '_three' => array()); ?> How could I sort that array so it ends up like so: Code: [Select] Array ( [_three] => Array ( ) [one] => Array ( ) [two] => Array ( ) ) Thanks!! I have a associative array and I need to compare it to a normal array. Code: [Select] associative will have anywhere from 2-8 of these ['name'] ['color'] ['uid'] Code: [Select] normal array will have anywhere from 1-8 names ['name'] What I need to do is get the name of the people that are in the associative array that are not in the normal array. I've tried all sorts of different loops and what not and I cant seam to get anything to work in every case. Code: [Select] Array ( [Comment] => Array ( [post_id] => 1 [name] => cc [email] => [body] => spam ) ) How can i check if email is empty or not? Is there any php built in function? Should i use foreach? I am just trying to use Associate array in another php file through session.
file1.php <?php $age = array(); $_SESSION["age"] = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43 file2.php <?php session_start(); foreach( $_SESSION["age"] as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>\n"; } ?> OUTPUT: PHP Notice: Undefined index: age in session.php on line 3 PHP Warning: Invalid argument supplied for foreach() in session.php on line 3 Why am I getting this error? Above is just example I tried to demonstrate for asking question for other issue, unfortunately I got new error in this example. But actual issue was, I was trying to plot graph using library which requires only Associate array, where the data is formed in file1.php. But I get only last index value displayed in file2.php even in graph or in echo. I don't understand why other values are not displayed in file2.php Please point me what is going wrong, Thanks. The title makes it sound more complicated than it is. I have a recurring function that searches for a specific value in a multi-dimensional array. When it finds it, it returns an array of the index. For example, if it found the value at $array[1][4][2][0], it would return an array like this: [0]=>1 [1]=>4 [2]=>2 [3]=>0 Here's the function. Code: [Select] <?php // Other Code /** * Find's the parent of an item * Unfortunately, it takes a bit more work than just using the loudspeaker at a grocery store * @param int $parent The parent to be searched for * @param array $array * @param array $cur_index */ private function findParent($parent, $array, $cur_index) { for($i = 0; $i < count($array); $i++) { // Search the array if($array[$i]['id'] == $parent) { // If the parent is found $cur_index[count($cur_index)] = $i; return array(true, $cur_index); } if(count($array[$i][1]) > 1) { // Call findParent again to search the child $cur_index[count($cur_index)] = $i; $found_in_child = $this->findParent($parent, $array[$i], $cur_index); if($found_in_child[0]) { return $found_in_child; } } } return array(false); // Return no matches } I need to be able to call that index using the keys from the key array (as we will call it). How can I do that? Thank you in advance for your help. I have a sequential multidimensional array with many outer rows where all the inner arrays have the same number of elements as another sequential array which represents metadata of the first array's inner arrrays. $keys: ["time","system1_typeA","system2_typeA","system1_typeB","system3_typeC","system2_typeB","system1_typeC"] $arrayValues: [ ["2020-06-27 07:40:06",2.16,9.25,9.44,7.76,5.43,1.12], ["2020-06-27 07:40:23",2.66,8.93,4.31,6.59,8.44,3.42], ["2020-06-27 07:41:24",8.71,2.78,8.92,6.58,3.65,4.38], ["2020-06-27 07:41:58",1.86,6.36,2.65,3.99,7.25,3.32], ["2020-06-27 07:42:33",8.71,3.66,8.82,8.54,8.22,4.51] ]
{ "time": ["2020-06-27 07:40:06", "2020-06-27 07:40:23", "2020-06-27 07:41:24", "2020-06-27 07:41:58", "2020-06-27 07:42:33"], "system1": { "typeA": [2.16, 2.66, 8.71, 1.86, 8.71], "typeB": [9.44, 4.31, 8.92, 2.65, 8.82], "typeC": [1.12, 3.42, 4.38, 3.32, 4.51] }, "system2": { "typeA": [9.25, 8.93, 2.78, 6.36, 3.66], "typeB": [5.43, 8.44, 3.65, 7.25, 8.22] }, "system3": { "typeC": [7.76, 6.59, 6.58, 3.99, 8.54] } } Is there much faster way to do so than the following? I would like to use a built in function like array_combine() if possible, but grouping by system and type creates an issue. function transform(array $keys, array $arrayValues):array { $map=[]; foreach ($keys as $key) { $map[] = explode('_',$key); } $count=count($keys); $newValues=[]; foreach ($arrayValues as $i=>$arrayValue) { $newValues['time'][]=$arrayValue[0]; for ($i = 1; $i < $count; $i++) { $newValues[$map[$i][0]][$map[$i][1]][]=$arrayValue[$i]; } } return $newValues; }
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 Hi guys. I have an associative array called $VisitorCountryID $VisitorCountryID = filter_countries(array('Country' => $_SESSION['UserCountryName'])); and the function filter_countries() returns all the information relating to the visitors country from the database. To find out what we have in the array, we do: print_r($VisitorCountryID); and it gives us: Array ( [14] => Array ( [CountryId] => 14 [Country] => Australia [FIPS104] => AS [ISO2] => AU [ISO3] => AUS [ISON] => 36 [Internet] => AU [Capital] => Canberra [Comment] => ISO includes Ashmore and Cartier Islands,Coral Sea Islands [sortOrder] => 1 ) ) Which is OK. Now i just want the CountryId which you can see in the array is 14 therefore I write: print_r($VisitorCountryID['CountryId']); Which should give me 14 but it return blank no output. I am surprised. What do you think is missing here. Any response / feedback always welcomed! Cheers! Hello all!! I need help with an associative array I've been working on. I'm not sure if I should have typed the weekday in the index because I'm supposed to use the getdate() function to pull the day of the week into the array. I'm also supposed to use string functions to pull apart the value where it's connected with the colon ":". I've tried using explode() and strtok but I don't quite understand how they work...just like the getdate()..I don't understand. Thanks for any 'nudge' in the right direction you can offer. Code: [Select] <?php $title = "Associative Array"; $heading = "Daily Specials"; $specials = array( "Sunday" =>"52in Flat Screen TV:425.00", "Monday" =>"Amplifier:145.00", "Tuesday" =>"HP Computer:355.00", "Wednesday" =>"500GB External Harddrive:99.00", "Thursday" =>"Internal Speakers:55.00", "Friday" =>"Ergonomic Keyboard:85.00", "Saturday" =>"Wacom Tablet:175.00", ); echo "<html> <head> <title> $title </title> </head> <body> <h1> $heading </h1> <pre>\n"; //prints left and right aligned headers with 30 spaces printf ("%-30s%30s\n", "Items", "Price"); printf ("%'-60s\n", ""); foreach ($specials as $key=>$value); { //prints the key left aligned and the value right aligned //formats to two decimals spaces printf ("%-20s%20.2f\n", $key, $value); echo " </pre>\n"; $delimeter=":"; $inventory=strtok($inventory,$delimeter); while(is_string($inventory)) { if($inventory) { echo " $inventory\n"; } $inventory=strtok($delimiter); } $inventory=explode($delimeter,$inventory); foreach ($items as $item=>$price) { echo" $item, $price\n"; } echo " </pre>\n"; "</body> </html>\n"; ?> Hello, I am not sure if you can help me or if this is the place but... I am running linux and php5.3.6 I am having problems that I did not experience on my Windows box and it has to do with arrays if ($answer['correct']) { (which contains 1 or 0) is throwing Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING removing the quotes works but just curious why it is not working and if there is a setting i can change Also $answers[] = $answer[id]; is throwing Parse error: syntax error, unexpected ']', expecting T_STRING or T_VARIABLE or T_NUM_STRING Thank you to anyone who might be able to help. I'm scraping a housing website with html source: Code: [Select] <tr><td> </td><td> Bedrooms </td><td> </td><td >3</td><td> </td></tr> <tr><td> </td><td> Full Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Partial Baths </td><td> </td><td >1</td><td> </td></tr> <tr><td> </td><td> Interior Sq Ft </td><td> </td><td >1,356</td><td> </td></tr> <tr><td> </td><td> Acres </td><td> </td><td >0.16</td><td> </td></tr> What i'm trying to do is create an associative array with only the details I want from the above. I've already got a function that steps through the HTML and creates an array element for each row with the contents of each <td> statement as follows: Code: [Select] $repl = array(" ", "(", ")"); $repl_with = array("", "", ""); foreach ($rows_feat as $id2 => $row2){ $features_raw = $scrape->fetchAllBetween('<td','</td>',$row2,true); //$features_data[str_replace($repl,$repl_with,strtolower(trim($features_raw[1])))] = trim($features_raw[3]); $countid=$countid+1; } The array produced by this would look like: features_raw[1] = Bedrooms features_raw[3] = 1 Basically, I want to take data like this: Beds 1 Baths 1 Garage Yes and create an array on the fly: House[beds]=1 House[baths]=1 House[garage]="yes" The problem is that the order of Beds, Baths and Garage changes. So on some house pages the order would be Baths, Garage, Beds.. etc. Any pointers out there? Thanks, Brett Hi there! Ok I've a very simple code he $character = array (name=>"Joe", occupation=>"Programmer", age=>30, "Learned language "=>"Java" ); print_r($character); echo "<br/>"; foreach ( $character as $key=>$val ){ print "$key = $val <br>"; } The output is: Code: [Select] Array ( [name] => Joe [occupation] => Programmer [age] => 30 [Learned language ] => Java ) name = Joe occupation = Programmer age = 30 Learned language = Java Now instead of returning all the other elements, I just need to display only the first element in the array that is the value 'Joe'. I tried $val[name]; Output I get is not what I want: Code: [Select] J P J All responses/feedbacks is always welcomed Thank you! i have problem to get the sum from the associative array. i have to get sum for the 3 result that being display from the array
rsort($sub); }
<HTML> <?php $arr = array("sue" => "betsy", "frank" => "marge"); ?> </HTML> This produces the following HTML page: "betsy", "frank" => "marge"); Its like when I use the => to make my associative array, the code thinks I'm closing the php codeblock and then just prints the rest of it to the screen... 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 |