PHP - Is There A Way To Remove Array Values Based On Its Value?
Hi,
I have an array filled with values like this: Code: [Select] string(1) "Acer 1" string(2) "Acer 2" string(3) "Dell 1" string(4) "Dell 2" string(5) "Dell 3" string(6) "Dell 4" string(7) "Acer 3" string(8) "Acer 4" Is there a way to successfully remove all array strings that starts with a given value like "Acer"? I tried with this snippet, does not work: Code: [Select] foreach($array as &$value) { if(preg_match("/^Acer/", $value)) { unset($value); } } Any ideas will be appreciated! Similar TutorialsHello. I am editing a plugin that is grabbing a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data. What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable. The current variable Code: [Select] $arrSlides returns several subarrays that look like something like this (I remove unimportant variables for the sake of brevity): Code: [Select] Array ( [0] => Array ( [slide_active] => 1 ) [1] => Array ( [slide_active] => 0 ) ) What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable Code: [Select] $arrSlides. I have tried a few array functions but have not had any luck. Any suggestions? Thanks in advance, Jason (1) I need to remove the lowest and higest values from an array. I need to actually remove the two lowest and two highest. I suppose the best thing would be to sort the array and then use a function that just drops the first and last values (twice). Is this the best way? Which function would drop the lowest / highest values? (2) I then need to get the remaining first and last (highest and lowest) values. $array[0] would get first, and revesing the order and $array[0] again would get the last. Is this the best way? 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?
When i click my submit button i am posting the following. Array ( [submitStaffOrder] => [staffMember] => Array ( [0] => 2 [1] => ANYCHEF1 ) [date] => Array ( [0] => 2020-02-18 [1] => 2020-02-18 ) [startTime] => Array ( [0] => 11:01 [1] => 10:10 ) [finishTime] => Array ( [0] => 11:01 [1] => 10:01 ) [delExisting] => Array ( [0] => [1] => toDel ) ) I would like to update/insert if delExisting is blank and delete if it has toDel in there. I have the following but i am pretty sure the if is not working. $date = $_POST['date']; $stime = $_POST['startTime']; $ftime = $_POST['finishTime']; $del = $_POST['delExisting']; $staff = $_POST['staffMember']; $stmt = $conn -> prepare(" INSERT IGNORE INTO ssm_staff_order (job_id, staff_id, staff_start_time, staff_finish_time, staff_start_date, staff_finish_date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE staff_start_time = VALUES(staff_start_time), staff_finish_time = VALUES(staff_finish_time); "); $delstmt = $conn -> prepare(" DELETE FROM ssm_staff_order WHERE staff_id = ? AND job_id = ? AND staff_start_date = ? "); foreach ($staff as $key => $staffId) { if ($del == '') { $start = $date[$key].' '.$stime[$key]; $finish = $date[$key].' '.$ftime[$key]; $stmt -> bind_param('isssss', $jid, $staffId, $start, $finish, $date[$key], $date[$key]); $stmt -> execute(); } if ($del == 'toDel') { $delstmt -> bind_param('sis', $staffId, $jid, $date[$key]); $delstmt -> execute(); } } } Can i do what i am trying to do or am i way off here?
I struggle with arrays Edited February 24, 2020 by AdamhumbugI've added a CSS class to the main menu of a Wordpress site and wish to remove the class if the browser width drops below a certain number. I've tried a number of different approaches but none has worked.
Some examples:
$(document).ready(function() { I have written code in php to connect and insert rows into a MSSQL database. i used odbc to connect database.user can enter his details through the form. after submitting the form the details are getting stored into a database. while inserting rows into a database am not trying to insert duplicate values . for this i have given if conditions.these conditions are able to notice the user cname and name exist in the database if the same name exist. but the else part after these conditions are not working i.e rows are not getting inserted. i put everything inside the while loop. how can i correct it? This is my php code. $connect = odbc_connect('ServerDB','sa', 'pwd'); //connects database $query2="select count(*) from company";//this is needer for loop through $result2=odbc_exec($connect,$query2); while(odbc_fetch_row($result2)); { $count=odbc_result($result2,1); echo "</br>","$count"; } $query1="select * from company"; $result1 = odbc_exec($connect, $query1); # fetch the data from the database while(odbc_fetch_row($result1)) { $compar[$count] = odbc_result($result1, 1); $namearray[$count] = odbc_result($result1, 2); if($compar[$count]==$_POST['cname']) { echo "<script> alert(\"cname Exists\") </script>"; } else if($namearray[$count]==$_POST['name']) { echo "<script> alert(\"Name Exists\") </script>"; } else { $query=("INSERT INTO company(cname,name) VALUES ('$_POST[cname]','$_POST[name]') "); $result = odbc_exec($connect, $query); echo "<script> alert(\"Row Inserted\") </script>"; } } Hi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) $username = $_POST['uid']; $email = $_POST['mail']; $password = $_POST['pwd']; $passwordRepeat = $_POST['pwd-repeat']; $date = $_POST['date2']; $stream = $_POST['relationship']; $sql1 = "INSERT INTO users (uidUsers, emailUsers, pwdUsers, relationship) VALUES (?, ?, ?, ?);"; $sql2 = "INSERT INTO Family1 (username, application_filed, relationship) VALUES (?, ?, ?);"; $sql3 = "INSERT INTO Family2 (username, application_filed, relationship) VALUES (?, ?, ?);"; mysqli_query($sql1, $conn); mysqli_query($sql2, $conn); mysqli_query($sql3, $conn); $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql2)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='nursing'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql3)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { mysqli_stmt_bind_param($stmt, "sss", $username, $date, $stream); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) ($username==$_SESSION['uid'] and $stream =='doctoral'); mysqli_stmt_execute($stmt); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } if (!mysqli_stmt_prepare($stmt, $sql1)) { header("Location: ../signup.php?error=sqlerror"); exit(); } else { $hashedPwd = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, "ssss", $username, $email, $hashedPwd, $stream); mysqli_stmt_execute($stmt); header("Location: ../signup.php?signup=success"); exit(); I was wondering if someone could point me in the right direction. I have this code. They idea I had behind it is to insert values into different tables depending on variables being passed. So when user fills out a form and selects $stream="nursing" I want results to go to table 'users' and 'Family1', but not 'Family2' table. and if user selects $stream='doctoral' results should go to table 'users' and 'Family2', and not go to 'Family1' But with my query I get results go to both table and also users table. And there is no restriction to what users selects, variable $stream being passed no matter what it is. Is this the wrong way to go here? Did I completely mess up the logic? Hi,
I am a bit of a MYSQL newbie so please bear with me. I have a database created about football/soccer stats. The database at the moment contains the following tables but more maybe added:
Players
Clubs
Seasons
Competitions
I will create php pages for these tables that add, edit and delete records for each. But the problem I can't get my head around is how to add a record that uses data from other tables, for example we would add a...
player -> club-season-competition
Lets say we want create a player called 'Joe Bloggs' and want to add his details, we need somehow for the page to display an option for club, season and competition. Maybe they can be drop down boxes but how does one fill those drop down boxes with records that are already added in the database for each table?
Thanks
This topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=315834.0 I have 3 tables w/ the following fields: Cities id | state_id | city_name States id | state_name New_cities id | state_id | city_name I am trying to write a script (and still working on it) that will INSERT new cities in cities WHERE New_cities.state_id = Cities.state_id. Obviously I am still in testing and results sort out, but honest to all hell, I might be going about this all wrong, and would appreciate any comments, criticism, assistance or feedback on what I am trying to do. <?php $query = "SELECT * FROM cities, states, new_cities"; if ($results = mysqli_query($cxn, $query)) { $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { if ($row['cities']['state_id'] == $row['new_cities']['new_state_id']) { $insert_city_query = "INSERT INTO cities id, new_state_id, city_name VALUES ('','$new_state_id','$city_name')" or mysqli_error(); } //if ($row['cities']['state_id'] == $row['new_cities']['new_state_id']) echo "$row[new_city_name]<br />"; } //while ($row = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) } //if ($results = mysqli_query($cxn, $query)) ?> 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. I have mysql select query shown below retrieving data from a database:
$sql = " SELECT student, sum( test_score ) as score FROM test INNER JOIN level ON test.level_id = level.level_id GROUP BY student" $result = $mysqli->query($sql, MYSQLI_STORE_RESULT); if($result) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { var_dump($row); } }On inspection of the retrieved array with var_dump(), i have these result below: array (size=2) 'John' => string 'English' (length=2) 'Score' => string '20' (length=3) array (size=2) 'Mary' => string 'Math' (length=3) 'Score' => string '35' (length=3) array (size=2) 'Samuel' => string 'Physics' (length=3) 'Score' => string '5' (length=3)How do I get at and print out the highest score from this set of array values within this context. I tried this echo max($row['count']) but i understandably got this feedback: Warning: max(): When only one parameter is given, it must be an array Thanks. 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. guys please help, i have an array(52,51,52) here i want to insert first & last elements into DB, not second one does not follows the series another array (52,52,53) in this case insert first 2 elements into DB since last element does not follow the series. how is this possible? I can't for the life of me understand how to perform this so I need some professional help here. I have a large array that contains some garbage every Nth and Nth + 1 element that needs to go away. array_filter doesn't work with keys but anyhow, i wouldn't know how to design the function. My keys are numeric, starting from 0. The keys I want to remove are part of this sequence: 8, 9, 18, 19, 28, 29 ... Can someone help me design a generic function to remove these keys? function filter_keys($array, $n, $offset) {} $new_array = filter_keys($array, 10, 8 ); I would maybe have to run this function twice, once for 8 offset and once for 9 offset. Hello guys, need some help. Let us say i have an array = 2011 ipad 2011 ipad review 2011 ipad price 2011 ipad design 2011 ipad reviews review 2011 ipad 2011 ipad feature I would like to review all the array elements that contain "review"...So the final array should look like 2011 ipad 2011 ipad price 2011 ipad design 2011 ipad feature Thanks I am trying to write a dirty script that removes duplicate rows from a multidimensional array. I want to be able to edit the function and spit the duplicates out to a CSV file. Here is my test file: $fullArray = array(array('Jim', 'Jones'), array('Pete', 'Pumpkin'), array('Barak', 'Obama'), array('Jason', 'Newstead'), array('Toby', 'Keith'), array('Jim', 'Jones'), array('Jim', 'Nelson')); echo "<h1>Original</h2>"; for($i=0; $i<count($fullArray); $i++) { echo $fullArray[$i][0] . " " . $fullArray[$i][1] . "<br />"; } echo "<h2>Checked</h2>"; $cleanArray = array(); $cay = array(); $nn=0; $dup=0; // Loop the entire input array foreach ($fullArray as $index => $item) { echo "foreach index:$index<br>"; // Start an internal pointer for ($f=0; $f<count($fullArray); $f++) { echo "for $f "; // if the index is lower or the same as the pointer, skip it to cut down on time if ($f > $index) { // if the rows are the same... if($fullArray[$f][0] == $item[0] && $fullArray[$f][1] == $item[1]) { echo "$item[0] DUP<br>"; // remove it from the array $cay = array_push($cleanArray, array($item[0], $item[1])); array_pop($fullArray[5]); $dup++; } else { // not a duplicate echo " not a dup<br>"; } } else { echo "ON THIS ONE<br>"; } } echo "<br><br>"; } echo"<br>$dup duplicates found<br><br>"; print_r($fullArray); echo "<br /><br>"; // print_r($item); print_r($cleanArray); ?> When I spit out the new fullArray variable, it still has an element from the duplicate record. This is what I get for the output of the full array after the duplicate was removed: Quote Array ( => Array ( => Jim [1] => Jones ) [1] => Array ( => Pete [1] => Pumpkin ) [2] => Array ( => Barak [1] => Obama ) [3] => Array ( => Jason [1] => Newstead ) [4] => Array ( => Toby [1] => Keith ) [5] => Array ( => Jim )[/b] [6] => Array ( => Jim [1] => Nelson ) ) So, I am making a system that shows if there are new posts or not. How I have it done is a singular array called "Read" will have all of the IDs of the read posts. It is entered in the database like so: $ID2= $_SESSION['UserID']; $ID2 = mysql_real_escape_string($ID2); $Readornot=mysql_query("SELECT * FROM forum_read WHERE Reader_ID='$ID2'"); $Readornot2=mysql_fetch_array($Readornot); if($ID2==0) { } else { if(empty($Readornot2)) { $Read1= array("Read" => $Get_TopicID); $Read2 = implode('-',$Read1); mysql_query("INSERT INTO forum_read (Reader_ID,`Read`) values ('$ID2','$Read2')") or die(mysql_error()); } else { $cr_topicid=$Readornot2['Read']; if(strpos($cr_topicid,'-')) { $cr_topicid=explode('-',$cr_topicid); if(!in_array($Get_TopicID,$cr_topicid,true)) { $Read0=implode('-',$cr_topicid); $Read1= array("Read" => $Read0, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } else { if($cr_topicid==$Get_TopicID) { } else { $Read1= array("Read" => $cr_topicid, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } } } It all works fine and dandy to the point where if it's in the database an icon will be black and white, and if its not it wont, signifying read or unread. What I need to do, however, is make it so when there is a new post, it takes all of the entries in the database with the topic ID out of the database, and strips the one part. What I thought of at first was to use str_replace to replace "-" . $TopicID . "-" with "-" But of course, that won't work, because the very first entry could be the topic ID, so it would just be $TopicID- and not -$TopicID- in the database. So, how would I go about doing this? Is there a built in function to remove empty array values for example: change Array ( [0] => Bob [1] => [2] => Ryan [3] => Jane ) to Array ( [0] => Bob [1] => Ryan [2] => Jane ) Thanks |