PHP Array: array filter with argument - php

I have this simple array in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
When supplied with 'client corp', the output should be the above array with only the first item.
So far I have this:
$selectedTree = array_filter($tree,"checkForTags");
function checkForTags($var){
$arr = $var->tags;
$test = in_array("client corp", $arr, true);
return ($test);
}
However, the result is that it's not filtering. When I echo $test, I get 1 all the time. What am I doing wrong?

Something like this should do the trick:
$selectedTree = array_filter(array_map("checkForTags", $tree ,array_fill(0, count($tree), 'client corp')));
function checkForTags($var, $exclude){
$arr = $var->tags;
$test = in_array($exclude, $arr, true);
return ($test ? $var : false);
}
array_map() makes sure you can pass arguments to the array. It returns each value altered. So in the returning array, some values are present, others are set to false. array_filter() with no callback filters all falsey values from that array and you are left with the desired result

The in_array() function returns TRUE if needle is found in the array and FALSE otherwise. So by getting 1 as a result that means that "client corp" is found.
Check PHP in_array() manual
You can user array_search() to return the array key instead of using in_array().

Related

Remove an array inside an array if one of the keys is null

i have 1 array with more arrays inside, and im trying to remove one of those arrays if they have a null key or its empty. Im doing this on PHP.
What i have:
Array
(
[0] => Array
(
[emp] =>
[fun] => 1
[data] =>
[data_d] =>
[desc] =>
)
[1] => Array
(
[emp] => teste
[func] => 1
[data] => 2021-08-30
[data_d] => 2021-09-01
[desc] => testetetetete
)
[2] => Array
(
[emp] => ersfewqef
[func] => 2
[data] => 2021-08-26
[data_d] => 2021-08-28
[desc] => dvgdgvqevgqe
)
)
This means that the [0] will be removed because has one or more empty values. Is this possible? I have no clue on how to do this.
You can use array_filter for this (maybe not the cleanest)
$result = array_filter($data, function($v, $k) {
#return true of false :: if true, then item is added in $result
return empty($v['emp']) || empty($v['data']) ... ;
}, ARRAY_FILTER_USE_BOTH );
You can use array_filter to filter elements of an array using a callback function.
If no callback is supplied, all empty entries of array will be removed. See empty() for how PHP defines empty in this case.
PHP reference
I think the other answers are on the right track with array_filter, but as far as how to identify which inner arrays have falsey values, you can just use array_filter again.
$result = array_filter($outer, fn($inner) => array_filter($inner) == $inner);
If an array is equal to its filtered value, then it does not contain any empty values, so using that comparison in your filter callback will remove all of the inner arrays with any empty values.
Just remember if you use this that any of the values listed here evaluate to false, so if you don't consider those "empty", you'll need to add a callback to the inner array_filter to make it more selective.
You can use array_filter and array_intersect to check for a number of needles in your haystack.
$newArray = array_filter($array, function($v) {
if( empty(array_intersect($v, [null, ""])) &&
empty(array_intersect(array_keys($v), [null, ""])) ) {
return $v;
}
});

Shuffle array losing data

I have an array and when I check this with print_r the output is:
Array ( [0] => metaalboutique.jpg [1] => asc.jpg [2] => thure.jpg [3] => stegge.jpg [4] => aws.jpg [5] => rsw.jpg [6] => pmm.jpg )
I want the export to be shuffled so I use shuffle() but when I check the output with print_r now I only see 1 as output.
$portfolio = array
(
'thure.jpg',
'rsw.jpg',
'pmm.jpg',
'asc.jpg',
'stegge.jpg',
'metaalboutique.jpg',
'aws.jpg'
);
$shuffled_portfolio = shuffle($portfolio);
print_r($portfolio);
print_r($shuffled_portfolio);
shuffle shuffles an array in place and returns a boolean to indicate if the shuffling succeeded (TRUE) or not (FALSE):
$portfolio = array
(
'thure.jpg',
'rsw.jpg',
'pmm.jpg',
'asc.jpg',
'stegge.jpg',
'metaalboutique.jpg',
'aws.jpg'
);
print_r($portfolio);
$success = shuffle($portfolio);
if ($success) {
# $portfolio is now shuffled
print_r($portfolio);
}
PHP shuffle function returns boolean value.
shuffle — Shuffle an array
bool shuffle ( array &$array )
&$array - the & sign means you are passing a reference of an array in that function.
Return Values
Returns TRUE (1) on success or FALSE(0) on failure.

PHP How to get key name from value if array is multidimensional

I have following array and getting this result:
Array
(
[0] => stdClass Object
(
[UnitIdx] => 10
[Title] => 순차
[Description] =>
[NumSteps] => 9
[ThumbnailPathName] => Level_1_Unit_thumbnail_Small.png
[Step_1] => 4
[Step_2] => 5
[Step_3] => 6
[Step_4] => 7
[Step_5] => 8
[Step_6] => 9
[Step_7] => 10
[Step_8] => 11
[Step_9] => 12
[Step_10] => 0
[Step_11] => 0
[Step_12] => 0
[Step_13] => 0
[Step_14] => 0
[Step_15] => 0
[Step_16] => 0
[Step_17] => 0
[Step_18] => 0
[Step_19] => 0
[Step_20] => 0
)
)
Now I want to find key form value. For example value is 11 so key is Step_8.
Any idea how to return key name from value?
Thanks.
You can search your key by value using array_search() and converting your Object into PHP array by typecasting, below is an example:
<?php
$object = array();
$object[0] = new StdClass;
$object[0]->foo = 1;
$object[0]->bar = 2;
echo "<pre>";
print_r($object);
echo "</pre>";
$key = array_search ('2', (array) $object[0]);
echo "<pre>";
print_r($key);
?>
Output:
Array
(
[0] => stdClass Object
(
[foo] => 1
[bar] => 2
)
)
bar
Take a look at this:
<?php
//this part of code is for prepare sample data which is similar to your data
$class = new stdClass;
$class->prop1 = 'prop1';
$class->prop2 = 'prop2';
$array = array($class);
//THIS IS METHOD FOR SEARCH KEY BY VALUE
print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); //you are looking for key for value 'prop1'
Check working fiddle: CLICK!
Explanation:
1) json_decode(json_encode($array[0]), true) - because you have in your array stdClass object, you can't use array_search function. So this line converts $array[0] element, which is stdClass object to an array. Now we can use array_search function to search key by specific value.
2) print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); - we are using array_search function to get key of array element which value is equal to prop1. Documentation of this function says:
array_search — Searches the array for a given value and returns the
corresponding key if successful
So we getting key corresponding to prop1 value, which is prop1. print_r function shows us result. Instead of that you can assign result of operation to a variable and use it in other parts of code, for example:
$variable = array_search('prop1',json_decode(json_encode($array[0]), true));

Remove duplicated elements of associative array in PHP

$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other'),
);
If it is duplicated removed it, so the result is as follows:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other')
);
Could any know to do this?
Thanks
Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:
array_unique($result, SORT_REGULAR);
The meaning of the SORT_REGULAR flag is:
compare items normally (don't change types)
And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).
array_unique does a strict comparison (=== in PHP), for arrays this means:
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Output (Demo):
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.
So try this:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);
Result:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
Serialization is very handy for such problems.
If you feel that's too much magic for you, check out this blog post
function array_multi_unique($multiArray){
$uniqueArray = array();
foreach($multiArray as $subArray){
if(!in_array($subArray, $uniqueArray)){
$uniqueArray[] = $subArray;
}
}
return $uniqueArray;
}
$unique = array_multi_unique($result);
print_r($unique);
Ironically, in_array is working for arrays, where array_unique does not.

Select only unique array values from this array

I have the following variable $rows:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH20
)
[2] => stdClass Object
(
[product_sku] => PCH19
)
[3] => stdClass Object
(
[product_sku] => PCH19
)
)
I need to create second array $second containing only unique values:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH19
)
)
But when i run array_unique on $rows, i receive:
Catchable fatal error: Object of class stdClass could not be
converted to string on line 191
array_unique()
The optional second parameter sort_flags may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
Also note the changenotes below
5.2.10 Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.
$values = array_unique($values, SORT_REGULAR);
$uniques = array();
foreach ($array as $obj) {
$uniques[$obj->product_sku] = $obj;
}
var_dump($uniques);
The default behavior of function array_unique() is to treat the values inside as strings first. So what's happening is that PHP is attempting to turn your objects into strings (which is throwing the error).
You can modify your function call like this:
$uniqueArray = array_unique($rows, SORT_REGULAR);
This will compare values without changing their data type.
Please check below code, I hope this will be helpful to you.
$resultArray = uniqueAssocArray($actualArray, 'product_sku');
function uniqueAssocArray($array, $uniqueKey)
{
if (!is_array($array))
{
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item)
{
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= false;
}
else
{
$replace=true;
}
if ($replace)
$uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}

Categories