PHP - Simple Array Splitting / Nth Output Question
Trying to do something that I think should be very simple. Let's assume that I have an array populated with the numbers 1 to 24 for this example.
I need to output these items in 4 columns to accomodate my CSS layout but still have them read from left to right, top to bottom. I also want this to be somewhat dynamic - I'm okay hardcoding it to split into 4 columns, but need it to handle any number of items in the array. I'm not sure if the best way to do this would be to split the original array into an array for each of the 4 columns, or to loop through the original array 4 times and output items 1+4, 2+4, and so on. Or maybe I should be using array_filter with some custom callback functions. I'm fine with any solution. The end result is echoing the array in the following groupings so I can surround each column with the appropriate column HTML for layout (in this case the array actually contains IMG urls): Column 1: 1, 5, 9, 13, 17, 21 Column 2: 2, 6, 10, 14, 18, 22 Column 3: 3, 7, 11, 15, 19, 23 Column 4: 4, 8, 12, 16, 20, 24 Any help would be appreciated! This one is driving me nuts and I know it should be relatively easier. Guess I should stick to HTML + CSS. Similar TutorialsHello. I have a newbie question regarding arrays: How can I echo an element's subsequent arrays and elements? For example Code: [Select] $pers = array("Steve" => array("eyes" => "green", "age" => "43", "race" => "caucasian")); and if I echo $pers["Steve"] to make it display: green 43 caucasian. Thanks. my php array knowledge is still basic and i can't seem to get this code to yield an answer in the form i want. i would like to be able to get at $m and $b separately so I can manipulate them. how, for example do i just print $m? Code: [Select] <?php var_dump( linear_regression(array(1, 2, 3, 4), array(1.5, 1.6, 2.1, 3.0)) ); /** * linear regression function * @param $x array x-coords * @param $y array y-coords * @returns array() m=>slope, b=>intercept */ function linear_regression($x, $y) { // calculate number points $n = count($x); // ensure both arrays of points are the same size if ($n != count($y)) { trigger_error("linear_regression(): Number of elements in coordinate arrays do not match.", E_USER_ERROR); } // calculate sums $x_sum = array_sum($x); $y_sum = array_sum($y); $xx_sum = 0; $xy_sum = 0; for($i = 0; $i < $n; $i++) { $xy_sum+=($x[$i]*$y[$i]); $xx_sum+=($x[$i]*$x[$i]); } // calculate slope $m = (($n * $xy_sum) - ($x_sum * $y_sum)) / (($n * $xx_sum) - ($x_sum * $x_sum)); // calculate intercept $b = ($y_sum - ($m * $x_sum)) / $n; return array("m"=>$m, "b"=>$b); } ?> Hey, Can someone please fix my code below? I simply want to add all values for $row[score1] in first if statement and add all values for $row[score2] in second if statement and then add them together to return final value . Code: [Select] while( $row = mysql_fetch_assoc($query)) { if($clanID==$row[clan1] && $row[score1] > $row[score2]) { $points[] = $row[score1]; } if($clanID==$row[clan2] && $row[score1] < $row[score2]) { $points[] = $row[score2]; } } return $points;. So lets say I echo the variables that I want added... Code: [Select] if($clanID==$row[clan1] && $row[score1] > $row[score2]) { $points[] = $row[score1]; echo $row['score1']."<br>"; } if($clanID==$row[clan2] && $row[score1] < $row[score2]) { $points[] = $row[score2]; echo $row['score2']."<br>"; } On page it returns as: 11 16 14 Add it together is 41 and this is what I want the output to be. Hope you understand I appreciate any help! P.S. I must be able to return final value OUTSIDE loop. Thanks. I will state right here that I've never really delved into PHP before, but I'm prying apart the code on my site (a programmer made it for me). I've figured out how to add more checkboxes onto the page, but I've run into a problem. Code: [Select] 'Artist' => array ( 'Cassiadawn', 'Cryptic', 'Diction', 'Glorfindel', 'Kyrislian', 'Russa', 'Ntkufreak', 'Taliba', 'Thunderbun', 'Velg', 'Lostdollie', 'Pookawitch') What I'm trying to do is replace 'Lostdollie', 'Pookawitch' with 'Lostdollie [R]', 'Pookawitch[R]'. How can I do this? I'd really appreciate any help anyone can give me! Hey guys I have an array and want to make it into a sting and separate each array segment by a comma...is there a function for this or should I just do it in a loop myself?...thanks Ok guys and gals I'm gettin' old! I know this is simple but I've spent way too much time on this now and am crying 'uncle'! I'm trying load a multi-dementional array with mysql_fetch_array results but I'm not getting it. Here's the rough basis for what I'm trying to do: $result = mysql_query("SELECT * FROM phpbb_profile_fields_data"); $row = mysql_fetch_array($result) or die(mysql_error()); $some_array = array( array( 'member_name' => $row['pf_firstname'] . " " . $row['pf_lastname'], 'member_title' => $row['pf_title'], 'member_employer' => $row['pf_employer'], ), array( 'member_name' => 'Janet', 'member_title' => '47', 'member_employer' => 'Husband', ), ); Okay, so that loads two $some_array elements with data. The first element has the first row of the database in question. Works fine but useless. So, with a "while ($row = mysql_fetch_array($result) )" what do I need to do to fill the $some_array with the query results? Thanks! if(in_array("b", $array)) { } The above checks to see if a value is present in an array, but how do I then retrieve the array key value from the matching value? $array[0] = "a"; $array[1] = "b"; $array[2] = "c"; So in the example, the answer is 1 (array key 1). Hi there, I have the following PHP code: <?php $books = array( array("title"=>"Book Title 1", "author"=>"Author 1", "publisher"=>"Publisher 1"), array("title"=>"Book Title 2", "author"=>"Author 2", "publisher"=>"Publisher 2"), array("title"=>"Book Title 3", "author"=>"Author 3", "publisher"=>"Publisher 3"), ); foreach ($books as $key => $value) { echo "$key : $value<br>"; } ?> I'm trying to loop through this code, but all it outputs is: 0: ARRAY 1: ARRAY 2: ARRAY -- It's not even pulling the proper $keys and $values. It works when there's just ONE array -- but not with this multidimensional array. Any ideas? Thanks! J I'll be creating a script that will get the keywords from uploaded pictures and what i cant figure out is how to actually get only the keywords from the iptc data this is the code i have for getting the iptc data right now: Code: [Select] <?php $size = getimagesize('images/Sections/pinkpanthers/20102011/Session1/1-15-11/1.jpg', $info); if(isset($info['APP13'])) { $iptc = iptcparse($info['APP13']); var_dump($iptc); ?> } and this outputs Code: [Select] array(4) { ["1#090"]=> array(1) { [0]=> string(3) "%G" } ["2#000"]=> array(1) { [0]=> string(2) "" } ["2#025"]=> array(1) { [0]=> string(5) "Tyler" } ["2#080"]=> array(1) { [0]=> string(15) "Christian" } } all i want from the above string is the Tyler Hey guys,
I have an array of names sorted alphabetically. I'm trying to loop through them and create new arrays keyed by the letters of the alphabet containing the names which start with that letter.
so in the end i'm trying to create something like this:
$newarray = array( 'a' => array('anna','alan','andrew'),
'b' => array('bert','ben','bob'), 'c' => array('cait','carry'), etc,etc ); thanks Hi All How do I go about splitting a multidimensional array into seperate smaller ones? Currently I have $grade[region][userid]=value. I'd like to split as $region1[userid]=value $region2[userid]=value $region3[userid]=value $region4[userid]=value $region5[userid]=value $region6[userid]=value Is there an inbuilt function for this? I'm using smarty and php to collect parameters from a user defined tag in cmsms that looks like this... Code: [Select] {schedule date="2010-11-13" time="7:05 p.m." location="Evansville" home="Oakland City" vs="Evansville" winner="University of Evansville" results="82-42"} {schedule date="2010-11-15" time="7:00 p.m." location="Oakland City" home="Oakland City" vs="OSU-Lima" winner="OSU-Lima" results="68-67 2OT"} etc... As you can see each {schedule tag above has the same home="" value. Thats because its schedule dates just for THAT team (i.e. Oakland City). So I may have 10 of these tags on the same page. But I also have other places where the schedule tag is used with a different $home name for another team. So basically I'm calling ALL these schedule tags into one for loop like this... Code: [Select] for ($i=0; $i < count($params['date']); $i++) { $date= $params['date']; $time=$params['time']; $location= $params['location']; $home= $params['home']; $vs= $params['vs']; $winner= $params['winner']; $results= $params['results']; $gameinfo = array("date", "time","location","home","vs","winner","results"); $game_info = compact($gameinfo); } All I want to do is spit back out the total wins for each $home team. I am pulling out my hair out trying to get this thing to work but no luck yet, even though I see a little light. This is what I got so far... Code: [Select] for ($i=0; $i < count($params['date']); $i++) { $date= $params['date']; $time=$params['time']; $location= $params['location']; $home= $params['home']; $vs= $params['vs']; $winner= $params['winner']; $results= $params['results']; $gameinfo = array("date", "time","location","home","vs","winner","results"); $game_info = compact($gameinfo); if($home == $winner) { $wins = array('team' => $winner, 'win' => count($winner)); } } $smarty->append('mwins',$wins); print '<pre>'; print_r($wins); print '</pre>'; and I get this... Code: [Select] Array ( [0] => Array ( [team] => Oakland City [win] => 1 ) [1] => Array ( [team] => Oakland City [win] => 1 ) [2] => Array ( [team] => Oakland City [win] => 1 ) [3] => Array ( [team] => Oakland City [win] => 1 ) [4] => Array ( [team] => Oakland City [win] => 1 ) [5] => Array ( [team] => Oakland City [win] => 1 ) [6] => Array ( [team] => Oakland City [win] => 1 ) [7] => Array ( [team] => Oakland City [win] => 1 ) [8] => Array ( [team] => Oakland City [win] => 1 ) [9] => Array ( [team] => Oakland City [win] => 1 ) [10] => Array ( [team] => Oakland City [win] => 1 ) [11] => Array ( [team] => Oakland City [win] => 1 ) [12] => Array ( [team] => Oakland City [win] => 1 ) [13] => Array ( [team] => Oakland City [win] => 1 ) [14] => Array ( [team] => Oakland City [win] => 1 ) [15] => Array ( [team] => Oakland City [win] => 1 ) [16] => Array ( [team] => Oakland City [win] => 1 ) [17] => Array ( [team] => Southern Indiana [win] => 1 ) [18] => Array ( [team] => Southern Indiana [win] => 1 ) [19] => Array ( [team] => Southern Indiana [win] => 1 ) [20] => Array ( [team] => Southern Indiana [win] => 1 ) [21] => Array ( [team] => Southern Indiana [win] => 1 ) [22] => Array ( [team] => Southern Indiana [win] => 1 ) [23] => Array ( [team] => Southern Indiana [win] => 1 ) [24] => Array ( [team] => Southern Indiana [win] => 1 ) [25] => Array ( [team] => Southern Indiana [win] => 1 ) [26] => Array ( [team] => Southern Indiana [win] => 1 ) [27] => Array ( [team] => Southern Indiana [win] => 1 ) [28] => Array ( [team] => Southern Indiana [win] => 1 ) [29] => Array ( [team] => Southern Indiana [win] => 1 ) [30] => Array ( [team] => Southern Indiana [win] => 1 ) [31] => Array ( [team] => Southern Indiana [win] => 1 ) [32] => Array ( [team] => Southern Indiana [win] => 1 ) [33] => Array ( [team] => Southern Indiana [win] => 1 ) [34] => Array ( [team] => Southern Indiana [win] => 1 ) [35] => Array ( [team] => Southern Indiana [win] => 1 ) [36] => Array ( [team] => Southern Indiana [win] => 1 ) [37] => Array ( [team] => Southern Indiana [win] => 1 ) etc... I want to take all the [win] values for each [team] and add them up this way my final array looks like this... Code: [Select] Array ( [0] => Array ( [team] => Oakland City [win] => 18 ) [1] => Array ( [team] => Southern Indiana [win] => 24 ) I know I'm so close but don't know how to solve the condition I need. Any suggestions would be great!!! bh I am trying to get rows from MYSQL table (attachment) based on: Select last five rows where status_id = 1 Select last two rows where status_id = 2*I did use UNION with two SELECT queries to get whole data as one array. Now on PHP side... I have first block for rows having status_id 1 so if there are rows having status_id 1 then PHP should display the data otherwise if there is no row having status_id 1 then PHP should print NO DATA only once. I have second block for rows having status_id 2 so if there are rows having status_id 2 then PHP should display the data otherwise if there is no row having status_id 2 then PHP should print NO DATA only once. I did use foreach loop then within loop i did use if condition to check status_id of rows. it works fine when i omit NO DATA part but when i add it. the result shows both rows and NO DATA in first block when there are one or more rows having status_id 1 but no row having status_id 2 Which made me believe that i was doing it the wrong way. Please guide me *PS: I know its PHP section the thread should be related to PHP problem but... is it right to use UNION in query? or should i post a new thread in relevant section for guidance?
Hello all, I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Hi guys, I want to create a simple database and use PHP to output the database to certain positions on a HTML page. I am basically trying to recreate this: http://bit.ly/dX4byI I want to have a form where the event info is selected from drop down box such as: Venue and Date then the the rest of the form data (event name, artists, opening times) will go into the right box depending on this. Does anyone have any pointers? Am I even going about this the right way?! I am wanting to create a basic product listing page for a product category called "Belts". My latest attempt was this, but I got an error: PHP Code: Code: [Select] $query = "select * from products"; $result = mysql_query($query); while($row=mysql_fetch_assoc($result)) { print ".$row['name'] where category = 'Belts'.$row['colour'] where category = 'Belts'"; } Quote PHP Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING This is what my MySQL table looks like: http://i54.tinypic.com/2j1si8w.png I image what I am trying to do will print "Somename Black, ProductName2 Brown"? I'm not really interested in styling at the moment, I just want to see the PHP-MySQL work at the most basic level. I am unsure what the error cosde means. Can anyone see a fault in my code? Hi all What I am trying to achieve is a for each loop for the following output Code: [Select] Array ( [result] => success [source] => getDirectory [success] => Array ( [0] => /root/mc/world/data/ [1] => /root/mc/world/level.dat [2] => /root/mc/world/level.dat_old [3] => /root/mc/world/players/ [4] => /root/mc/world/players/herghost.dat [5] => /root/mc/world/region/ [6] => /root/mc/world/region/r.-1.0.mcr [7] => /root/mc/world/region/r.0.0.mcr [8] => /root/mc/world/session.lock [9] => /root/mc/world/uid.dat ) ) How would I go about saving each path from the [success] output? Basically I wish to loop through the array and delete the files. Many Thanks I'm kind of a beginner, but I really need this script and I'm not sure how quite to do it as needed... With some html forms I need it so you can type a name in then click submit, then (with php) it will save that text into a text file or something. Later, when I hit a different button it will randomly display one of those texts/names from before. Hi,I
I'm trying to setup Paypal Pro on a website - have everything working - but need to grab the 4th & 6th key values from the results given from the Paypal response and having difficulty with the task.
See the code that prints the response and the response sent from Paypal below - I need to grab the values for [TRXRESULT] and [TRXRESPMSG]
echo('<pre>'); print_r($PayFlow->getResponse()); echo('</pre>');and here's the response I get from Paypal on script execution - this is an example of a failed transaction: Paypal Response Array ( [RESULT] => 36 [RPREF] => RPC5B24581A2 [RESPMSG] => Transaction failed: Fail to obtain approval for the online transaction [TRXRESULT] => 23 [TRXPNREF] => EUJPC36F2092 [TRXRESPMSG] => Invalid account number: Unsupported Credit Card type )Again, I want to grab the values from [TRXRESULT] and [TRXRESPMSG] and assign them to local variables so i can work with them within the local php script. Example: $trxresult and $trxrespmsg Here's part of the class (file name is Class.Payflow.php find on Github) that pertains to this snippet of code in question: Class.Payflow.php /** * @uses Gets the response from Paypal. * @access Public * @param None. * @return Array/String - Returns an array of Paypal's response or empty string if not return. * @example $PayFlow->getResponse(); */ public function getResponse() { if($this->response) { return $this->response; } else { return ''; } }Thanks in advance for help w/this one! I have an array and I would like to insert commas and the word 'and' to make a sentence using an array. For example... $sports = array(baseball, soccer, tennis); Ted played baseball, soccer and tennis or Ted played baseball, soccer, boxing and tennis What's the best way to do this? |