Unset batch of keys in an array from another array elements - php

I have an array:
$array = Array
(
[0] => qst
[1] => insert_question_note
[2] => preview_ans
[3] => _preview
[4] => view_structure_answer_preview
[5] => index
}
I need to unset the array keys based on elements in
$array_elements_to_be_remove = array('qst','_preview'); // or any string start with '_'
I tried to use:
$array_key = array_search('qst', $array);
unset($array[$array_key]);
$array_key_1 = array_search('_preview', $array);
unset($array[$array_key_1]);
Is there any other better ways to search batch of elements in $array ?
I expect that if I can use array search like this:
$array_keys_to_be_unset = array_search($array_elements_to_be_remove, $array);
I found a way to search the string if it is start with '_' as below:
substr('_thestring', 0, 1)
Any ideas how to do that?

You could use array_filter
$array = Array(
0 => 'qst',
1 => 'insert_question_note',
2 => 'preview_ans',
3 => '_preview',
4 => 'view_structure_answer_preview',
5 => 'index'
);
$array_elements_to_be_remove = array('qst', '_preview'); // or any string start with '_'
$new_array = array_filter($array, function($item)use($array_elements_to_be_remove) {
if (in_array($item, $array_elements_to_be_remove) || $item[0] == '_')
return false; // if value in $array_elements_to_be_remove or any string start with '_'
else
return true;
});
var_dump($new_array);

You can use php build function array_diff:
$arr=array_diff($array1, $array2);
Refer this php docs

Related

How can I sort the result of array_merge() function?

Here is my code:
<?php
$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];
print_r(array_merge($arr1, $arr2));
/* Array
(
[o] => vote
[u] => true
[p] =>
[v] => digit
)
Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?
Note: I don't care about the order of other items.
So this is expected result:
/* Array
(
[o] => vote
[u] => true
[v] => digit
[p] =>
)
One simple way I found was to use rsort, which Sort an array in reverse order. Like so (run):
$merged = array_merge($arr1, $arr2);
rsort($merged);
The output:
Array
(
[0] => vote
[1] => true
[2] => digit
[3] =>
)
You could also go with a simple foreach (example) or even usort (example)
One possible approach that preserves the order of non-empty elements would be:
$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];
$merged = $arr1 + $arr2;
$empty = array_filter($merged, function($var) {
return $var == "";
});
$nonEmpty = array_diff_assoc($merged, $empty);
$sorted = $nonEmpty + $empty;
function sort($array){
$emptyKey ="";
foreach ($array as $key => $value){
if(empty($value){
$emptyKey = $key;
break;
}
}
unset($array[$emptyKey]);
$array[$emptyKey] = "";
return $array;
}
usort($partner_names, function($a1, $b1) {
return strcasecmp($a1['PARTNER_USERNAME'], $b1['PARTNER_USERNAME']);
});
We should use strcasecmp for case insensitive strings

Randomly select words from multi-dimension array

I have a multi-dimensional array and from where i want to choose 11 different words. Each word from different array index.
Here is the array link: My multi-dimensional array
array (
'w' =>
array (
0 => 'walls',
1 => 'well',
2 => 'why',
),
'e' =>
array (
0 => 'end',
),
'a' =>
array (
0 => 'advantage',
1 => 'afford',
2 => 'affronting',
3 => 'again',
4 => 'agreeable',
5 => 'ask',
6 => 'at',
),
'c' =>
array (
0 => 'children',
1 => 'civil',
2 => 'continual',
)
);
My Desire Output:
From w => well
From e => end
From a => again
and so on.
Output like: array(well, end, again, ...) as array.
Use the following code:
$f = array_keys($result); // grouping the indices, namely, the characters
$a = "";
for($c=0;$c<count($f);$c++){
$a .= $f[$c];
} // grouping the indices stored in array $f to a string, $a
$words = array();
for($c=0;$c<11;$c++){
$random = $a[rand(0,strlen($a)-1)];
$k = $result[$random];
// $k stores the array of the character index, stored in $result
$random2 = rand(0,count($k)-1);
$words[$c] = $k[$random2];
// choose a word from a given character array
$a = preg_replace("/".$random."/","",$a);
// remove the character from $a to prevent picking words which start with the same character
}
print_r($words);
I've tested and it was proved working
https://3v4l.org/qi1VP
You can achieve this usin array_rand() function :
PHP
$words = [];
$limit = 3; //Replace this with your limit, 11
$count = 0;
shuffle($array);
foreach($array as $key => $value) {
$words[] = $value[array_rand($value)];
$count++;
if ($limit == $count) {
break;
}
}
EvalIn
Check Online, and let me know.
using shuffle and array_slice you can get what you want.
A shuffle function makes your array random, and array slice slice 11 sub array from it.
Array slice takes 3 argument, first one is the array, second one is the offset from where you want to start and last one how much you need to cut.
$words = array();
shuffle($result);
$res = array_slice($result, 0, 11);
foreach($res as $key => $value){
shuffle($value);
$words[] = $value[0];
}
print_r($words);

Delete array value containing given text

I have this array:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "sbm=SOME_TEXT",
[2] => "obm=SOME_TEXT"
);
How can I remove array's element(s) containing value obm or sbm (which is always at the top of the string in the array) and update indexes?
Example 1:
print_r(arrRemove("smb", $array));
Output:
$array = array(
[0] => "obm=SOME_TEXT",
[1] => "obm=SOME_TEXT"
);
Example 2:
print_r(arrRemove("omb", $array));
Output:
$array = array(
[0] => "sbm=SOME_TEXT"
);
You can simply loop through the array using a foreach and then use strpos() to check if the array contains the given input string, and array_values() to update the indexes:
function arrRemove($str, $input) {
foreach ($input as $key => $value) {
// get the word before '='
list($word, $text) = explode('=', $value);
// check if the word contains your searchterm
if (strpos($word, $str) !== FALSE) {
unset($input[$key]);
}
}
return array_values($input);
}
Usage:
print_r(arrRemove('obm', $array));
print_r(arrRemove('sbm', $array));
Output:
Array
(
[0] => sbm=SOME_TEXT
)
Array
(
[0] => obm=SOME_TEXT
[1] => obm=SOME_TEXT
)
Demo!
Maybe something like this?
$newarray = array_values(array_filter($oldarray, function($value){
return strpos($value, 'obm') !== 0;
}
));
This is handled by PHP
php.net/manual/en/function.array-pop.php
array_pop() pops and returns the last value of the array , shortening the array by one element.

PHP multidimensional array to simple array

Which method is best practice to turn a multidimensional array
Array ( [0] => Array ( [id] => 11 ) [1] => Array ( [id] => 14 ) )
into a simple array? edit: "flattened" array (thanks arxanas for the right word)
Array ( [0] => 11 [1] => 14 )
I saw some examples but is there an easier way besides foreach loops, implode, or big functions? Surely there must a php function that handles this. Or not..?
$array = array();
$newArray = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$newArray[] = $temp[0];
}
See it here in action: http://viper-7.com/sWfSbD
Here you have it in function form:
function array_flatten ( $array )
{
$out = array();
foreach ( $array as $key => $val )
{
$temp = array_values($val);
$out[] = $temp[0];
}
return $out;
}
See it here in action: http://viper-7.com/psvYNO
You could use array_walk_recursive to flatten an array.
$ret = array();
array_walk_recursive($arr, function($var) use (&$ret) {
$ret[] = $var;
});
var_dump($ret);
If you have a multidimensional array that shouldn't be a multidimensional array (has the same keys and values) and it has multiple depths of dimension, you can just use recursion to loop through it and append each item to a new array. Just be sure not to get a headache with it :)
Here's an example. (It's probably not as "elegant" as xdazz", but it's an alternate without using "use" closure.) This is how the array might start out like:
Start
array (size=2)
0 =>
array (size=1)
'woeid' => string '56413072' (length=8)
1 =>
array (size=1)
'woeid' => string '56412936' (length=8)
Then you might want to have something like this:
Target
array (size=2)
0 => string '56413072' (length=8)
1 => string '56412936' (length=8)
You can use array_walk_recursive
Code
$woeid = array();
array_walk_recursive($result['results']['Result'], function ($item, $key, $woeid) {
if ($key == 'woeid') {
$woeid[] = $item;
}
}, &$woeid);

weird php array

my php array looks like this:
Array (
[0] => dummy
[1] => stdClass Object (
[aid] => 1
[atitle] => Ameya R. Kadam )
[2] => stdClass Object (
[aid] => 2
[atitle] => Amritpal Singh )
[3] => stdClass Object (
[aid] => 3
[atitle] => Anwar Syed )
[4] => stdClass Object (
[aid] => 4
[atitle] => Aratrika )
) )
now i want to echo the values inside [atitle].
to be specific i want to implode values of atitle into another variable.
how can i make it happen?
With PHP 5.3:
$result = array_map(function($element) { return $element->atitle; }, $array);
if you don't have 5.3 you have to make the anonymous function a regular one and provide the name as string.
Above I missed the part about the empty element, using this approach this could be solved using array_filter:
$array = array_filter($array, function($element) { return is_object($element); });
$result = array_map(function($element) { return $element->atitle; }, $array);
If you are crazy you could write this in one line ...
Your array is declared a bit like this :
(Well, you're probably, in your real case, getting your data from a database or something like that -- but this should be ok, here, to test)
$arr = array(
'dummy',
(object)array('aid' => 1, 'atitle' => 'Ameya R. Kadam'),
(object)array('aid' => 2, 'atitle' => 'Amritpal Singh'),
(object)array('aid' => 3, 'atitle' => 'Anwar Syed'),
(object)array('aid' => 4, 'atitle' => 'Aratrika'),
);
Which means you can extract all the titles to an array, looping over your initial array (excluding the first element, and using the atitle property of each object) :
$titles = array();
$num = count($arr);
for ($i=1 ; $i<$num ; $i++) {
$titles[] = $arr[$i]->atitle;
}
var_dump($titles);
This will get you an array like this one :
array
0 => string 'Ameya R. Kadam' (length=14)
1 => string 'Amritpal Singh' (length=14)
2 => string 'Anwar Syed' (length=10)
3 => string 'Aratrika' (length=8)
And you can now implode all this to a string :
echo implode(', ', $titles);
And you'll get :
Ameya R. Kadam, Amritpal Singh, Anwar Syed, Aratrika
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
echo $item->atitle;
}
}
to get them into an Array you'd just need to do:
$resultArray = array();
foreach($array as $item){
if(is_object($item) && isset($item->atitle)){
$resultArray[] = $item->atitle;
}
}
Then resultArray is an array of all the atitles
Then you can output as you'd wish
$output = implode(', ', $resultArray);
What you have there is an object.
You can access [atitle] via
$array[1]->atitle;
If you want to check for the existence of title before output, you could use:
// generates the title string from all found titles
$str = '';
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$str .= $v->title;
}
}
echo $str;
If you wanted these in an array it's just a quick switch of storage methods:
// generates the title string from all found titles
$arr = array();
foreach ($array AS $k => $v) {
if (isset($v->title)) {
$arr[] = $v->title;
}
}
echo implode(', ', $arr);
stdClass requires you to use the pointer notation -> for referencing whereas arrays require you to reference them by index, i.e. [4]. You can reference these like:
$array[0]
$array[1]->aid
$array[1]->atitle
$array[2]->aid
$array[2]->atitle
// etc, etc.
$yourArray = array(); //array from above
$atitleArray = array();
foreach($yourArray as $obj){
if(is_object($obj)){
$atitleArray[] = $obj->aTitle;
}
}
seeing as how not every element of your array is an object, you'll need to check for that.

Categories