PHP - Array - Remove Every Nth Key Starting From X
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. Similar TutorialsI have a form with some dropdownlist that get populated dynamically(depends on what the user chooses) with jquery and an xml file. In the form I have a button that takes the info and populates another form with the values of the ddl. I have coded script which populates the second form with jquery and the name of each input get dynamically added like so: Code: [Select] <input type="text" value="'+model+'" name="Model_'+model+'" id="'+model+'" readonly size="'+model.length+'" /> <input type="text" value="'+model+'" name="Model'+model+'" id="'+model+'" readonly size="'+model.length+'" />> <input type="text" value="'+color+'" name="Color'+color+'" id="'+color+'" readonly size="'+color.length+'" /> <input type="text" value="'+part+'" name="Part'+part+'" id="'+part+'" readonly size="'+part.length+'" /> <input type="text" value="$'+price+'" name="Price'+price+'" id="'+price+'" readonly size="'+price.length+'" /> <input type="text" value="'+qty+'" name="Quantity'+qty+'" id="'+qty+'" readonly size="'+qty.length+'" /> <input type="text" value="'+total+'" name="Total'+total+'" id="'+total+'" readonly size="'+total.length+'" /> What I want to do is grab the name of the element and remove the underscore and everything else form rileft to right so I am left with just the word before the underscore. I tried using substr($key,0,-28) but that wont work since everything after the underscore will have a different length. I was wondering if there is a way i can keep everything before the underscore and remove the underscore and everything after that. Thanks in advance for any input I get. I am wondering whether there is a way to do a foreach loop for an array, without starting at index[0]. Say, for example, I wanted to start displaying the contents of a 20 item array starting at index 5, what is the best way to do it? I know of this way, but it seems too crude (ie. there has to be a better way): $count = 0; foreach($array as $item) { if ($count > 5) {echo $item;} $count++; } Any other ideas?? 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? Just a quick one, new area for me. I have an array which is looped against another array, if the two values from each ever match then an event occurs, if not then something else. If a match does occur i then want to remove the said value from one of the arrays... is this really all i need to do, seems too simple: unset($saved_dont_use[$j]); 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 ) ) 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 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? 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 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! Hi guys! i got this code: Code: [Select] <? $x = "abcde"; str_split($x); for ($k=0; $k<=119; $k++){ $ax = array($x[0],$x[1],$x[2],$x[3],$x[4]); shuffle($ax); $text = implode("", $ax) . ""; echo $text; echo "<br />"; } ?> if you test it you see that it is working but giving me allot of duplicates results! there is a way to ignore duplicaes while it is runing? thanx. Hello. 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 Hello I have a while loop which outputs countrys from the database (im making a "filter by" function). For example, the loop outputs: Denmark Belgium Holland Brazil Japan Brazil Denmark I want to sort these alphabetically and then remove duplicates... Can somebody explain to me how? I don't know how to get them into an array to do it... Doing an API call and want to remove duplicates so I can display the products by brand. Problem I am having now is when I try to display the brands, I am getting duplicate brands. When I display the brands I am getting Nike, Nike, Reebook. When I just want, Nike, Reebok. My Code Code: [Select] <?php $results = array(); //array from API call $results2 = $results['data']; function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); } $results3 = multi_unique($results2); foreach ($results3 as $var) { echo $var['brand']; ?> <br /> <?php } ?> The array Code: [Select] { "errors": [ ], "warnings": [ ], "data": [ { "url": "http://[...]", "image_url": "[...]", "image_thumb_url": "[...]", "keyword": "Red Running Shoes", "description": "Red Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": null, "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588778", "isbn": null, "sales": 23 }, { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Blue Running Shoes", "description": "Blue Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588779", "isbn": null, "sales": 12 } { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Black Running Shoes", "description": "Black Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Reebok", "upc": "0944554779", "isbn": null, "sales": 12 } ], "coupons": [ ], "countryCode": "US", "page": 1, "limit": 10, "totalRecords": 3 } Hi all, Is there a function or method to delete element from current position in array without knowing the index. For example: $ar = array( 1, 2, 3, "test", 4, 5, "test2" ); while( $v = current( $ar ) ) { if( key( $ar ) == "test" ) { // remove element from the array where key equals "test" // i could count every cycle and splice from that index but i wonder can that be done without it // i am looking at the php array functions but i can't find any that will delete from element from current position in array echo 'key( $ar ) je test. key( $ar ): ' . key( $ar ); } next( $ar ); } One thing that i don't understand is that when i run example above the "test" key is found and when i echo it it gives me 0. Can anyone let me know what I am doing wrong. I am sure it will (after the fact) be obvious, but I don't see it right now. Wish to remove all array elements which do not implement ValidatorCallbackInterface. Thanks <?php interface ValidatorCallbackInterface{} class ValidatorCallback implements ValidatorCallbackInterface{} function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input, function($v) { return $v instanceOf ValidatorCallbackInterface; }); } function recursive_unset(&$array) { foreach ($array as $key => $value) { if (is_array($value)) { recursive_unset($value); if(empty($value)) { unset($array[$key]); } } elseif(!$value instanceOf ValidatorCallbackInterface) { unset($array[$key]); } } } $validatorCallback = new ValidatorCallback(); $rules=[ 'callbackId'=>"integer", 'info'=>[ 'arrayofobjects'=>[$validatorCallback], 'foo1'=>'bar1' ], 'foo2'=>'bar2', 'bla'=>[ 'a'=>'aa', 'b'=>'bb', ], 'singleobject'=>$validatorCallback ]; echo('original rules'.PHP_EOL); var_dump($rules); $desiredrules=[ 'info'=>[ 'arrayofobjects'=>[$validatorCallback] ], 'singleobject'=>$validatorCallback ]; echo('desired rules'.PHP_EOL); var_dump($desiredrules); echo('array_filter_recursive'.PHP_EOL); var_dump(array_filter_recursive($rules)); echo('recursive_unset'.PHP_EOL); recursive_unset($rules); var_dump($rules);
original rules array(5) { ["callbackId"]=> string(7) "integer" ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["foo2"]=> string(4) "bar2" ["bla"]=> array(2) { ["a"]=> string(2) "aa" ["b"]=> string(2) "bb" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } desired rules array(2) { ["info"]=> array(1) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } array_filter_recursive array(1) { ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } recursive_unset array(2) { ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } }
When I remove 1 session item using this it works fine when I select more than 1 item to be removed I get unexpected results, I have checked the outputted html to see what positions get echoed into the remove check box and they are correct, so I guess the problem lies in my remove code here is the part of the form that sends the remove check box <?php for ($basket_counter=0;$basket_counter<$_SESSION['ses_basket_items'];$basket_counter++) { $price=sprintf("%01.2f",$ses_basket_price[$basket_counter]); $quantity=$ses_basket_amount[$basket_counter]; $code=$ses_basket_stockcode[$basket_counter]; $itemID=$ses_basket_id[$basket_counter]; $name=$ses_basket_name[$basket_counter]; $image=$ses_basket_image[$basket_counter]; $size=$ses_basket_size[$basket_counter]; $sizechoice=$ses_basket_sizechoice[$basket_counter]; // create array from sizes and make the option box selections if ($sizechoice!="" && (!in_array($sizechoice, array('One Size', 'one size', 'free size', 'Free Size', 'Adjustable', 'adjustable')))) { // add size trigger $sizelist="add"; //create the array $sizepick=explode(",", $sizechoice); } else { $sizepick=$sizechoice; } // adjust gst for AU customers if ($country=='AU') { $price=sprintf("%01.2f",($price*1.1)); $unit=sprintf("%01.2f",($price/$quantity)); } else { $unit=sprintf("%01.2f",($price/$quantity)); } ?> <tr> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input type="checkbox" name="remove[<?php echo $basket_counter; ?>]" value="<?php echo $basket_counter; ?>" /></td> and here is the part of the code that processes the removal of the items $remove = $_POST['remove']; if (isset($remove) && ($remove!='')) { foreach($remove AS $key => $remove_position){ array_splice ($ses_basket_name, $remove_position, 1); array_splice ($ses_basket_amount, $remove_position, 1); array_splice ($ses_basket_price, $remove_position, 1); array_splice ($ses_basket_stockcode, $remove_position, 1); array_splice ($ses_basket_image, $remove_position, 1); array_splice ($ses_basket_size, $remove_position, 1); array_splice ($ses_basket_sizechoice, $remove_position, 1); array_splice ($ses_basket_id, $remove_position, 1); $_SESSION['ses_basket_items']--; } } I am using a form with checkboxes named remove[$remove_position] and the positions in the form are correct for each item in the array, but when I select more than 1 item to delete they are not always the correct items only the first 1 selected. What am I doing wrong here?? (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 have users in my database with many stored points ie age, gender, interests etc. about 20 points in all.
I have a table of products that I want to recommend only applicable products. They each have saved like minage, maxage, gender, interest etc for the ideal consumer. ie dress gender=f
This is the bare bones of what I have so far:
$result = mysql_query("SELECT * FROM user_table WHERE hash='$session_id'"); $rowuser = mysql_fetch_array($result); $result = mysql_query("SELECT * FROM products"); $rowproducts = mysql_fetch_array($result);So now I have $rowuser['gender'] = m , how do I remove all from $rowproducts where gender = f? Is there a best way to do this knowing I have about 20 points to go through before I am left with an array with just the best selection of products for this user in it? started learning php yesterday at w3schools was looking for a great forum to ask questions as i go along. bumped into phpfreaks. looking forward to mastering the art
But I need help in an issue I have been having for awhile now. Some reason when I try to call for online status it does not work sometimes i can get it to show the default code 1 which means online. But I am trying to get it to say Online and Offline and so on. I do not get what I am doing wrong my website using mysql so not sure if its having trouble reading the database or what. here is the code...
<?php class steam { public $api = STEAM_API; public $returnUrl = URL; public $user = array(); function __construct() { $this->setUserInfo(); } function isLoggedin() { if(isset($_SESSION['steam'])) { return true; } return false; } function showLogoutButton() { echo "<br /><a href=\"logout.php\">Logout</a>"; //logout button } function steamlogin() { require_once(INCLUDES.'/openid.php'); try { // Change 'localhost' to your domain name. $openid = new LightOpenID($this->returnUrl); //dump($openid); if(!$openid->mode) { if(isset($_GET['login'])) { $openid->identity = 'http://steamcommunity.com/openid'; header('Location: ' . $openid->authUrl()); } echo "<a href=\"?login\"><img src=\"http://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_small.png\"></a>"; } elseif($openid->mode == 'cancel') { echo 'User has canceled authentication!'; } else { if($openid->validate()) { $id = $openid->identity; $ptn = "/^http:\/\/steamcommunity\.com\/openid\/id\/(7[0-9]{15,25}+)$/"; preg_match($ptn, $id, $matches); $_SESSION['loginid'] = $matches[1]; //die('Here'); header('Location: index.php'); exit; } else { echo "User is not logged in.\n"; } //die('here we are'); } } catch(ErrorException $e) { echo $e->getMessage(); } } function doLogout() { if(isset($_POST['steamid'])) { unset($_POST['steamid']); } header('Location: index.php'); exit; } function setUserInfo() { global $DB; if($this->isLoggedin()) { // Grab the info from the session $userData = $DB->getUserById($_SESSION['steam']); if(isset($userData['steamid'])) { $this->user = $userData; } else { unset($_SESSION['steam']); die('Could not get user'); } } elseif(isset($_SESSION['loginid'])) { $url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.$this->api.'&steamids='.$_SESSION['loginid']; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true); $content = curl_exec($ch); curl_close($ch); $content = json_decode($content, true); $_SESSION['steam'] = $_SESSION['loginid']; // Set the database values $values = array( 'steamid' => $content['response']['players'][0]['steamid'], 'communityvisibilitystate' => $content['response']['players'][0]['communityvisibilitystate'], 'profilestate' => $content['response']['players'][0]['profilestate'], 'personaname' => $content['response']['players'][0]['personaname'], 'lastlogoff' => isset($content['response']['players'][0]['lastlogoff']) ? $content['response']['players'][0]['lastlogoff'] : '', 'profileurl' => $content['response']['players'][0]['profileurl'], 'avatar' => $content['response']['players'][0]['avatar'], 'avatarmedium' => $content['response']['players'][0]['avatarmedium'], 'avatarfull' => $content['response']['players'][0]['avatarfull'], 'personastate' => $content['response']['players'][0]['personastate'], 'timecreated' => $content['response']['players'][0]['timecreated'], 'onlineoffline' => $this->user['personastate'] == 1 ? 'Online' : 'Offline', 'status' => $this->getOnlineStatus() ); if($values['lastlogoff'] == '') { $values['lastlogoff'] = 'NA'; } else { $values['lastlogoff'] = date("m/d/Y", $values['lastlogoff']); } // Are updating the user info or adding them? $userExists = $DB->getUserById($_SESSION['steam']); if(isset($userExists['steamid'])) { // We have this user, lets update their info $DB->update('users', $values, array('steamid' => $_SESSION['steam'])); } else { // New user, lets insert them $id = $DB->insert('users', $values); } unset($_SESSION['loginid']); $this->setUserInfo(); } } function getOnlineStatus($values) { switch($this->user['onlineoffline']) { case '0': default: $state = 'Offline'; break; case '1': $state = 'Online'; break; case '2': $state = 'Busy'; break; case '3': $state = 'Away'; break; case '4': $state = 'Snooze'; break; case '5': $state = 'Looking to trade'; break; case '6': $state = 'Looking to play'; break; } return $state; } ?>This is basically my entire code that calls the steam api. Here is the echo function I use to try and call it on a profile.php page... echo "<br /><strong>Online:</strong> " . $steam->user['onlineoffline'] . " ";So I would really appreciate it if someone can help me. I been trying to figure out this for the past week and its starting to drive me nuts and loose motivation on my project. Everything else works great minus this one issue. I have pretty much asked everywhere I can think of and no help. I use a function to call my database hint the global $DB; in my functions just to give you anymore information I can. $steam variable I believe is coming from my class at the very top of my code that is were $steam comes from. Thanks Edited by soslidesigns, 12 August 2014 - 01:50 PM. |