Removing elements from an array whose value matches a specified string - php

I have an array that looks like this:
Array ( [0] => Vice President [1] => [2] => other [3] => Treasurer )
and I want delete the value with other in the value.
I try to use array_filter to filter this word, but array_filter will delete all the empty values, too.
I want the result to be like this:
Array ( [0] => Vice President [1] => [2] => Treasurer )
This is my PHP filter code:
function filter($element) {
$bad_words = array('other');
list($name, $extension) = explode(".", $element);
if(in_array($name, $bad_words))
return;
return $element;
}
$sport_level_new_arr = array_filter($sport_level_name_arr, "filter");
$sport_level_new_arr = array_values($sport_level_new_arr);
$sport_level_name = serialize($sport_level_new_arr);
Can I use another method to filter this word?

array_filter() is the right function. Ensure your callback function has the correct logic.
Try the following:
function other_test($var) {
// returns whether the value is 'other'
return ($var != 'other');
}
$new_arr = array_filter($arr, 'other_test');
Note: if you want to reindex the array, then you could call $new_arr = array_values($new_arr); after the above.

foreach($sport_level_name_arr as $key => $value) {
if(in_array($value, $bad_words)) {
unset($sport_level_name_arr[$key])
}
}

This will create two arrays and will find the difference. In the second array we will put the elements to exclude:
array_values(array_diff($arr,array("other")));

If the callback function returns true, the current value from input is returned into the result array. PHP Manual
So you need to do return true; in your filter(); function instead of return $element; to make sure that no empty values are removed.

Related

wordpress $wpdb select results to an array

$wp->get_results will return an array and formats the array depends if the second parameter is specified; if not, it is default to an object, right? But my question is it possible to retrieve results then store it the an array? Like this $arr = array(1,2,3,4,5)? What my main concern is this.. I want to search in the array if the value is present.
Now I can't do a in_array if the returned results is like this.
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
Any help would be much appreciated. Thanks.
EDITED
my $arr would look like this
Array ( [0] => stdClass Object ( [code] => 8 [id] => ) [1] => stdClass Object ( [code] => 1 [id] => ) )
EDITED
Found a solution:
if (in_array(array('1'), $arr) {
// found value
}
You can not match directly, for matching, it you will have to do something like this :
$arr = array(array('1'), array('2'), array('3'), array('4'), array('5'));
foreach($arr as $newar)
{
if (in_array('2',$newar))
{
echo 'hello';
}
}
I'm not really following the problem here, but assuming you want to find a specific value inside the wpdb results......
foreach($arr as $key => $row) {
if($row->code == $VALUE_YOU_WANT_TO_MATCH) {
// do something
break;
}
}
Note: $arr is an array of objects, its not a multidimensional array.
say for example I want to check if if code = 1 exist in my result.
foreach($arr as $myarr){
if ($myarr->code == "1"){
echo "record was found\n";
break;//this line makes the foreach loop end after first success.
}
}

PHP arrays: How to get the index where an element is

Here’s the following array:
Array
(
[1] => Array
(
[0] => 10
[1] => 13
)
[2] => Array
(
[0] => 8
[1] => 22
)
[3] => Array
(
[0] => 17
[1] => 14
)
)
Then I have
$chosenNumber = 17
What I need to know is:
First) if 17 is in the array
Second) the key it has (in this case [0])
Third) the index it belongs (in this case [3])
I was going to use the in_array function to solve first step but it seems it only works for strings ..
Thanks a ton!
function arraySearch($array, $searchFor) {
foreach($array as $key => $value) {
foreach($value as $key1 => $value1) {
if($value1 == $searchFor) {
return array("index" => $key, "key" => $key1);
}
}
}
return false;
}
print_r(arraySearch($your_array, 17));
You should look using these :
in_array()
array_search()
You have used array_search function
$qkey=array_search(value,array);
You use array_search:
$index = array_search($chosenNumber, $myArray);
if($index){
$element = $myArray[$index];
}else{
// element not found
}
array_search returns false if the element was not found, the index of the element you were looking for otherwise.
If a value is in the array multiple times, it only returns the key of the first match. If you need all matches you need to use array_keys with the optional search_value parameter specified:
$indexes = array_keys($myArray, $chosenNumber);
This returns a (possibly empty) array of all indexes containing your search value.
array_keys()
Return all the keys or a subset of the keys of an array
array_values()
Return all the values of an array
array_key_exists()
Checks if the given key or index exists in the array
in_array()
Checks if a value exists in an array
You can find more information here http://www.php.net/manual/en/function.array-search.php

php - adding values in an array

I'm trying to loop through a multidimensional array, and add a new sub array. My code doesn't return any errors, but it also doesn't add the new item.
I have the following code:
foreach ($data['switches'] as $switch) {
foreach ($switch['atags'] as $attributelist) {
$nohardwareAttribFound = false;
foreach ($attributelist as $attribute) {
$pos = strpos(trim($attribute),'$attr_2_');
if ($pos !==false) {
//echo 'in the loop';
//found it. extract and exit loop
$modelnumber = substr(trim($attribute),8);
$hardwaremodel = array();
$hardwaremodel['tag'] = 'hardware_model:'.$modelnumber;
array_push($switch['atags'],$hardwaremodel);
print_r($switch);
//echo '<br>=====<br>';
$nohardwareAttribFound = true;
}
}//end foreach ($attributelist
}// end foreach ($switch['atags']
if ($nohardwareAttribFound==false) {
$hardwaremodel['tag'] = 'Unknown';
array_push($switch['atags'],$hardwaremodel);
}//end if
}// end foreach ($data['switches']
I would like the data to look like:
[atags] => Array (
[0] => Array ( [tag] => $id_365 )
[1] => Array ( [tag] => $typeid_8 )
[2] => Array ( [tag] => $any_object )
[3] => Array ( [tag] => $casd )
[4] => Array ( [tag] => $unmounted )
[5] => Array ( [tag] => $no_asset_tag )
[6] => Array ( [tag] => $attr_2_1086 )
[7] => Array ( [tag] => $untagged )
[8] => Array ( [tag] => hardware_model:1086 ) ) )
where the last array - element [8], represents a new subarray that I've added. The print_r() statement looks correct, but when I loop through the results that are passed to my view, i can see that in fact, a new tag array has not been added.
Do i need to some sort of a replace instead of the array_push()?
If it's not a good idea to modify an array while looping through it, could I simply check to see if an item exists.
how would i check if the ['atags'] array for each switch contains a [tag] with a value that looks like "$attr_2_NNNN" where N is a number? For example, check out element 6 in the sample array above. The challenge is that it's not always element 6, and you're not always guaranteed that a tag will have the attr_2 value.
I know there is an in_array() function ... i will try something like:
if (in_array(array('$attr_2_'), $switches['atags']))
I have a bug with the logic around the $nohardwareAttribFound variable, which i'm going to fix.
Thanks
First of all: it is not advised to change an array or collection while you are iterating over it.
If you really want to do it like this, then you should take $switch by reference instead of by value. Otherwise you can change $switch to whatever you want, it will not be reflected in the $data['switches'] array.
To take $switch by reference just add the &:
foreach ($data['switches'] as &$switch) {
}
Check out foreach in PHP manual.
EDIT After studying your code, I think this is what you are looking for:
foreach ($data['switches'] as &$switch) {
$hardwaremodel = array();
$hardwaremodel['tag'] = NULL; // initialize to NULL so we can check at the end of the loop if we have found a hardwaremodel or not (so we don't need that bool)
foreach ($switch['atags'] as $attributelist) {
foreach ($attributelist as $attribute) {
$pos = strpos(trim($attribute), '$attr_2_');
if ($pos !== false) {
$modelnumber = substr(trim($attribute), 8);
$hardwaremodel['tag'] = 'hardware_model:' . $modelnumber;
break;
}
}
if ($hardwaremodel['tag'] !== NULL)
break; // exit the loop because we already found a tag
}
if ($hardwaremodel['tag'] === NULL)
$hardwaremodel['tag'] = 'hardware_model:unknown';
// Note that this is a safe place to modify the $switch array
// as we are not currently iterating it
array_push($switch['atags'], $hardwaremodel);
}
Everytime you enter the loop your interation variable (ie. $switch) is a copy - youre not modifying the original array $data. To do that you need to modify the full path like:
array_push($data['switches']['atags'], $newVal)
Or you can pass by reference when you enter the loop like:
foreach ($data['switches'] as &$switch)
{
// ...
}
I think you should replace
foreach ($data['switches'] as $switch)
with
foreach ($data['switches'] as &$switch)
Using a reference should do.
Note: use unset($switch) afterwards to destroy the reference.

PHP - Create a single array from a multidimensional array based on key name

I know there are a lot of answers on multi-dimensional arrays but I couldn't find what I was looking for exactly. I'm new to PHP and can't quite get my head around some of the other examples to modify them. If someone could show me the way, it would be much appreciated.
An external service is passing me the following multidimensional array.
$mArray = Array (
[success] => 1
[errors] => 0
[data] => Array (
[0] => Array (
[email] => me#example.com
[id] => 123456
[email_type] => html
[ip_opt] => 10.10.1.1
[ip_signup] =>
[member_rating] => X
[info_changed] => 2011-08-17 08:56:51
[web_id] => 123456789
[language] =>
[merges] => Array (
[EMAIL] => me#example.com
[NAME] => Firstname
[LNAME] => Lastname
[ACCOUNT] => ACME Ltd
[ACCMANID] => 123456adc
[ACCMANTEL] => 1234 123456
[ACCMANMAIL] => an.other#example.com
[ACCMANFN] => Humpty
[ACCMANLN] => Dumpty
)
[status] => unknown
[timestamp] => 2011-08-17 08:56:51
[lists] => Array ( )
[geo] => Array ( )
[clients] => Array ( )
[static_segments] => Array ( )
)
)
)
The only information I'm interested in are the key/value pairs that are held in the array under the key name 'merges'. It's about the third array deep. The key name of the array will always be called merges but there's no guarantee that its location in the array won't be moved. The number of key/value pairs in the merges array is also changeable.
I think what I need is a function for array_walk_recursive($mArray, "myfunction", $search);, where $search holds the string for the Key name (merges) I'm looking for. It needs to walk the array until it finds the key, check that it holds an array and then (preserving the keys), return each key/value pair into a single array.
So, for clarity, the output of the function would return:
$sArray = Array (
[EMAIL] => me#example.com
[NAME] => Firstname
[LNAME] => Lastname
[ACCOUNT] => ACME Ltd
[ACCMANID] => 123456adc
[ACCMANTEL] => 1234 123456
[ACCMANMAIL] => an.other#example.com
[ACCMANFN] => Humpty
[ACCMANLN] => Dumpty
)
I can then move on to the next step in my project, which is to compare the keys in the single merges array to element IDs obtained from an HTML DOM Parser and replace the attribute values with those contained in the single array.
I probably need a foreach loop. I know I can use is_array to verify if $search is an array. It's joining it all together that I'm struggling with.
Thanks for your help.
Would this work?
function find_merges($arr)
{
foreach($arr as $key => $value){
if($key == "merges") return $value;
if(is_array($value)){
$ret = find_merges($value);
if($ret) return $ret;
}
}
return false;
}
It would do a depth-first search until you either ran out of keys or found one with the value merges. It won't check to see if merges is an array though. Try that and let me know if that works.
Here is a general purpose function that will work it's way through a nested array and return the value associated with the first occurance of the supplied key. It allows for integer or string keys. If no matching key is found it returns false.
// return the value a key in the supplied array
function get_keyval($arr,$mykey)
{
foreach($arr as $key => $value){
if((gettype($key) == gettype($mykey)) && ($key == $mykey)) {
return $value;
}
if(is_array($value)){
return get_keyval($value,$mykey);
}
}
return false;
}
// test it out
$myArray = get_keyval($suppliedArray, "merges");
foreach($myArray as $key => $value){
echo "$key = $value\n";
}
A recursive function can do this. Returns the array or FALSE on failure.
function search_sub_array ($array, $search = 'merges') {
if (!is_array($array)) return FALSE; // We're not interested in non-arrays
foreach ($array as $key => $val) { // loop through array elements
if (is_array($val)) { // We're still not interested in non-arrays
if ($key == $search) {
return $val; // We found it, return it
} else if (($result = search_sub_array($array)) !== FALSE) { // We found a sub-array, search that as well
return $result; // We found it, return it
}
}
}
return FALSE; // We didn't find it
}
// Example usage
if (($result = search_sub_array($myArray,'merges')) !== FALSE) {
echo "I found it! ".print_r($result,TRUE);
} else {
echo "I didn't find it :-(";
}
So you want to access an array within an array within an array?
$mergeArray = NULL;
foreach($mArray['data'] as $mmArray)
$mergeArray[] = $mmArray['merges'];
Something like that? If merges is always three deep down, I don't see why you need recursion. Otherwise see the other answers.
Here's another approach, mostly because I haven't used up my iterator quota yet today.
$search = new RegexIterator(
new RecursiveIteratorIterator(
new ParentIterator(new RecursiveArrayIterator($array)),
RecursiveIteratorIterator::SELF_FIRST),
'/^merges$/D', RegexIterator::MATCH, RegexIterator::USE_KEY
);
$search->rewind();
$merges = $search->current();
array_walk_recursive() is brilliant for this task! It doesn't care what level the key-value pairs are on and it only iterates the "leaf nodes" so there is not need to check if an element contains a string. Inside of the function, I am merely making a comparison on keys versus the array of needles to generate a one-dimensional result array ($sArray).
To be clear, I am making an assumption that you have predictable keys in your merges subarray.
Code: (Demo)
$needles=['EMAIL','NAME','LNAME','ACCOUNT','ACCMANID','ACCMANTEL','ACCMANMAIL','ACCMANFN','ACCMANLN'];
array_walk_recursive($mArray,function($v,$k)use(&$sArray,$needles){if(in_array($k,$needles))$sArray[$k]=$v;});
var_export($sArray);
Output:
array (
'EMAIL' => 'me#example.com',
'NAME' => 'Firstname',
'LNAME' => 'Lastname',
'ACCOUNT' => 'ACME Ltd',
'ACCMANID' => '123456adc',
'ACCMANTEL' => '1234 123456',
'ACCMANMAIL' => 'an.other#example.com',
'ACCMANFN' => 'Humpty',
'ACCMANLN' => 'Dumpty',
)

Find the key of a corresponding array value

I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index of the value "UD" etc.
Array
(
[0] => LN
[1] => TYP
[2] => UD
[3] => LAG
[4] => LO
)
how can i do that??
array_search function is meant for that usage
snipet:
$index = array_search('UD', $yourarray);
if($index === false){ die('didn\'t found this value!'); }
var_dump($index);
Use array_search:
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
$key = array_search('UD', $array); // $key = 2;
if ($key === FALSE) {
// not found
}
Your best bet is:
array_keys() returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
print_r(array_keys($array, "UD"));
Array
(
[0] => 2
)
Possible considerations for not using array_search()
array_search() If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
I suggest array_flip:
$value = "UD";
$new = array_flip($arr);
echo "result: " . $new[$value];
Just a note: some of these array_* functions are substantially more useful in PHP 5.3 with the addition of anonymous functions. You can now do things like:
$values = array_filter($userArray, function($user)
{
// If this returns true, add the current $user object to the resulting array
return strstr($user->name(),"ac");
});
Which will return all elements in our imaginary array of user objects that contain "ac" ("Jack","Jacob") in their name.
This has been possible in the past with create function, or simply by defining a function beforehand, but this syntax make it a lot more accessible.
http://ca2.php.net/manual/en/functions.anonymous.php
$array = Array(0 => LN, 1 => TYP, 2 => UD, 3 => LAG, 4 => LO);
$arrtemp = array_keys($array,'UD');
echo 'Result : '.$arrtemp[0];
I use array_keys to find it.

Categories