Unsetting arrays with a specific value in a multidimensional array? - php

I am checking that certain elements in sub-arrays in a multidimensional array are not equal to a value and un-setting the array with that value from the multi array. I built a function so that I could easily implement this, however it doesn't appear to be working.
function multi_unset($array, $unset) {
foreach($array as $key=>$value) {
$arrayU = $array[$key];
$check = array();
for($i = 0; $i < count($unset); $i++) { // produces $array[$key][0, 2, 3]
array_push($check, $arrayU[$unset[$i]]);
}
if(in_array("-", $check)) {
unset($array[$key]);
}
}
return $array;
}
$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test"));
$unset = array(0, 2, 3); // keys in individual arrays to check
multi_unset($arr, $unset);
print_r($arr); // Should output without $arr[0]
In this case, I'm checking if each sub-array has a "-" value in it and un-setting the array from the multi array. I am only checking specific keys in the sub-arrays (0, 2, 3) however it outputs an array without any changes. I figured I must have some scoping wrong and tried to use "global" everywhere possible, but that didn't seem to fix it.

Modified your version a bit and handled the return value.
function multi_unset($array, $unset)
{
$retVal = array();
foreach($array as $key => $value)
{
$remove = false;
foreach($unset as $checkKey)
{
if ($value[$checkKey] == "-")
$remove = true;
}
if (!$remove)
$retVal[] = $value;
}
return $retVal;
}
$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test"));
$unset = array(0, 2, 3);
$arr = multi_unset($arr, $unset);
print_r($arr);

You may want to do some reading into Passing by Reference vs passing by value in PHP.
Heres some code that works with the given data set....
// Note the pass by reference.
function multi_unset(&$array, $unset) {
foreach($array as $pos => $subArray) {
foreach($unset as $index) {
$found = ("-" == $subArray[$index]);
if($found){
unset($subArray[$index]);
// Ver 2: remove sub array from main array; comment out previous line, and uncomment next line.
// unset($array[$pos]);
}
$array[$pos] = $subArray; // Ver 2: Comment this line out
}
}
//return $array; // No need to return since the array will be changed since we accepted a reference to it.
}
$arr = array(array("-", "test", "test", "test"), array("test", "test", "test", "test"));
$unset = array(0, 2, 3);
multi_unset($arr, $unset);
print_r($arr);

Related

Updating any value in multi-dimensional arrays

I'm trying to update values in a multi-dimensional array (using a function so it can be done dynamically), but my approach of looping through each values doesn't seem to work. I tried different solutions offered on stackoverflow but I still can't seem to make it work as a function (with dynamic keys). Here is a simple example with a 2 level array, but it should work on any level.
function updateArrayValue($array,$key_to_find,$new_value){
foreach($array as $key => $value){
if($key == $key_to_find){
$value = $new_value;
break; // Stop the loop
}
}
return $array;
}
$array = array("001"=>"red", "002"=>"green", "003"=>array("003-001"=>"blue", "003-002"=>"yellow"));
$array = updateArrayValue($array,"003-001","purple");
var_dump($array);
You need recursion call of function and set new values. Not value only but changed deep array.
function updateArrayValue($array,$key_to_find,$new_value){
foreach($array as $key => $value){
// if value is not an array then try set new value if is search key
if(!is_array($value)){
if($key == $key_to_find) {
$array[$key] = $new_value;
}
}
else {
// otherwise call function again on value array
$array[$key] = updateArrayValue($value, $key_to_find, $new_value);
}
}
return $array;
}
$array = array(
"001"=> "red",
"002"=> "green",
"003"=> array(
"003-001"=> "blue",
"003-002"=> "yellow"
));
$newArray = updateArrayValue($array,"003-001","purple");
var_dump($newArray);

Using array_keys to search a multidimensional array with a partial array

$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
print_r (array_keys($testArray, array(1,3, "file2.png"))); // Works
print_r (array_keys($testArray, array(1,3))); // Does not work.
As shown in the code above, I'd like to be able to quickly find an array in a multidimensional array but only specify two of the values.
One way to do this is to filter the testArray down to those number of keys using array_map, then use array_search to get the key.
$testArray = array(
array(1,2,"file1.png"),
array(1,3,"file2.png"),
array(1,4,"file3.png")
);
$search = [1,3];
$filtered = array_map(function ($item) use ($search){
return array_slice($item, 0, count($search));
}, $testArray);
$key = array_search($search, $filtered);
if ($key !== false){
print_r($testArray[$key]);
} else {
echo 'not found';
}
You can filter the array by testing which ones contain the values by computing the intersection and then get those keys:
$keys = array_keys(array_filter($testArray,
function($v) {
return count(array_intersect([1,3], $v)) == 2;
}));
You can extend it with a search $s variable:
$s = [1,3];
$keys = array_keys(array_filter($testArray,
function($v) use($s) {
return count(array_intersect($s, $v)) == count($s);
}));
This will return the keys for any sub array that contains [1,3], [3,1] or even [3,"file2.png",1], order is irrelevant.
To check them in order:
$s = [1,3];
$keys = array_keys(array_filter($testArray,
function($v) use($s) {
return count(array_intersect_assoc($s, $v)) == count($s);
}));
Loop through your data and slice each triplet, taking the first two items, and compare these to your needle. Return the file given a match.
<?php
$data = array(
array(1, 2, "file1.png"),
array(1, 3, "file2.png"),
array(1, 4, "file3.png")
);
$get_file_from_coords = function(array $coords) use ($data) {
foreach($data as $v) {
if (array_slice($v, 0, 2) == $coords) {
return $v[2];
}
}
};
echo $get_file_from_coords([1, 3]);
Output:
file2.png
(Note: If you have more than one file associated with your co-ordinate pair you'll need to adapt the code to return an array of matches.)
You don't necessarily need to slice or do anything fancy here. You can just compare like so:
[$v[0], $v[1]] == $coords
Your array data
$testArray = [
[1, 2, 'file1.png'],
[1 ,3, 'file2.png'],
[1 ,4, 'file3.png']
];
Specify what your search match conditions into an array
$matching = [1, 3];
Loop through your array data to find matches using array_intersect_assoc() which compares values and keys between two arrays. Store the actual found key and its values into a new array.
foreach ($testArray as $index => $contents) {
if (array_intersect_assoc($matching, $contents) == $matching) {
$found[$index] = $contents;
}
}
Display the results
echo '<pre>';
!empty($found) ? print_r($found) : print_r('not found');

how can I get my php array data to persist?

When I query the data within the foreach loop it works, but makes a duplicate for each pass in the loop. I try to var_dump it anywhere else outside the loop and the data isn't there. Why won't my data persist outside the forEach loop?
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green",
5=>"Green", 6=>"Blue", "green"=>"green",
"two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN",
"ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
/* found here:
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
Expectation: When I run the function it should replace all instances of "green" with "not green" and save those into a $newArray. I have it returning $newArray but even then it doesn't seem to match up that the values are being saved into the newArray, hence why I'm doing var_dump to check if it's even working (it appears to not be)
Results: as it is setup, I get an empty array returned to me...It seems to work somewhat if I move var_dump($newArray) to within the foreach loop but that then duplicates the data for each pass.
if you want var_dump $newArray out side the function then you should declare $newArray as global in your function
<?php
$old_array = [10-2, 13=>"3452", 4=>"Green", 5=>"Green", 6=>"Blue", "green"=>"green", "two"=>"green" ,"2"=>"green" , "rulebreak" =>"GrEeN", "ninja"=>" Green ", ["blue" => "green", "green"=>"green", 2 => "itsGreen"] ];
$newArray = array();
function filter_Green($array) {
global $newArray;
$find = "green";
$replace = "not green";
/* Same result as using str_replace on an array, but does so recursively for multi-dimensional arrays */
if (!is_array($array)) {
/* Used ireplace so that searches can be case insensitive */
return str_ireplace($find, $replace, $array);
}
foreach ($array as $key => $value) {
$newArray[$key] = $value;
if ($key == "green") {
$newArray[$key] = "not green";
}
if ($value == "green") {
$newArray[$value] = "not green";
}
}
return $newArray;
}
filter_Green($old_array);
var_dump($newArray);
?>
But instead of declaring global in function, use returned value by filter_Green($old_array); as below
$result = filter_Green($old_array);
var_dump($result);

PHP array check if value in specific key exists

I am using PHP 5.5.12.
I have the following multidimensional array:
[
{
"id": 1,
"type":"elephant",
"title":"Title of elephant"
},
{
"id": 2,
"type":"tiger",
"title":"Title of tiger"
},
{
"id": 3,
"type":"lion",
"title":"Title of lion",
"children":[{
"id": 4,
"type":"cow",
"title":"Title of cow"
},
{
"type":"elephant",
"title":"Title of elephant"
},
{
"type":"buffalo",
"title":"Title of buffalo"
}]
}
]
I am iterating this array using foreach loop.
The array key type must be in elephant, tiger and lion. If not, then the result should return false.
How can I achieve this?
So you want to check if your $myArray contains a value or not:
// first get all types as an array
$type = array_column($myArray, "type");
// specify allowed types values
$allowed_types = ["lion", "elephant", "tiger"];
$count = count($type);
$illegal = false;
// for loop is better
for($i = 0; $i < $count; $i++)
{
// if current type value is not an element of allowed types
// array, then both set the $illegal flag as true and break the
// loop
if(!in_array($type[$i], $allowed_types)
$illegal = true;
break;
}
Since you're using PHP5.5.12, you can make use of array_column.
$arr = json_decode($json, true);
//Walk through each element, only paying attention to type
array_walk( array_column($arr, 'type'), function($element, $k) use(&$arr) {
$arr[$k]['valid_type'] = in_array($element, array('lion', 'tiger', 'elephant'));
});
From here, each element in the array ($arr) will have a new key valid_type with a boolean value - 1 if the type is valid, 0 if it isn't.
https://eval.in/350322
Is this something that you are looking for?
foreach($your_array as $item) {
if (!array_key_exists('type', $item)) {
return FALSE;
}
}
function keyExists($arr, $key) {
$flag = true;
foreach($arr as $v) {
if(!isset($v[$key])) {
$flag = false;
break;
}
}
return $flag;
}
Hope this helps :)

PHP Deep Extend Array

How can I do a deep extension of a multi dimensional associative array (for use with decoded JSON objects).
I need the php equivalent of jQuery's $.extend(true, array1, array2) with arrays instead of JSON and in PHP.
Here's an example of what I need (array_merge_recursive didn't seem to do the same thing)
$array1 = ('1'=> ('a'=>'array1a', 'b'=>'array1b'));
$array2 = ('1'=> ('a'=>'array2a', 'c'=>'array2b'));
$array3 = array_extend($array1, $array2);
//$array3 = ('1'=> ('a'=>'array2a', 'b'=>'array1b', 'c'=>'array2b'))
Notice how array2 overrides array1 if it has same value (like how extension of classes works)
If you have PHP 5.3.0+, you can use array_replace_recursive which does exactly what you need:
array_replace_recursive() replaces the values of array1 with the same
values from all the following arrays. If a key from the first array
exists in the second array, its value will be replaced by the value
from the second array. If the key exists in the second array, and not
the first, it will be created in the first array. If a key only exists
in the first array, it will be left as is. If several arrays are
passed for replacement, they will be processed in order, the later
array overwriting the previous values.
This might be what you're looking for:
function array_extend(&$result) {
if (!is_array($result)) {
$result = array();
}
$args = func_get_args();
for ($i = 1; $i < count($args); $i++) {
// we only work on array parameters:
if (!is_array($args[$i])) continue;
// extend current result:
foreach ($args[$i] as $k => $v) {
if (!isset($result[$k])) {
$result[$k] = $v;
}
else {
if (is_array($result[$k]) && is_array($v)) {
array_extend($result[$k], $v);
}
else {
$result[$k] = $v;
}
}
}
}
return $result;
}
Usage:
$arr1 = array('a' => 1, 'b' => 2, 'c' => 3);
$arr2 = array('b' => 'b', 'd' => 'd');
array_extend($arr1, $arr2);
print_r($arr1); // array('a' => 1, 'b' => 'b', 'c' => 3, 'd' => 'd')
// or, to create a new array and leave $arr1 unchanged use:
array_extend($arr3, $arr1, $arr2);
print_r($arr3); // array('a' => 1, 'b' => 'b', 'c' => 3, 'd' => 'd')
// or, use the return value:
print_r(array_extend($arr1, $arr2)); // but this will also modify $arr1
I use this in the same way I use angular.extend(dst, src) and jQuery.extend().
function extend($base = array(), $replacements = array()) {
$base = ! is_array($base) ? array() : $base;
$replacements = ! is_array($replacements) ? array() : $replacements;
return array_replace_recursive($base, $replacements);
}
Example:
si() is a utility sanitize function that grabs $_POST or $_GET and returns an array.
$s = extend(array(
'page' => 1,
'take' => 100,
'completed' => 1,
'incomplete' => 1,
), si());
Taken from array_merge docs:
function array_extend($a, $b) {
foreach($b as $k=>$v) {
if( is_array($v) ) {
if( !isset($a[$k]) ) {
$a[$k] = $v;
} else {
$a[$k] = array_extend($a[$k], $v);
}
} else {
$a[$k] = $v;
}
}
return $a;
}
You should use: https://github.com/appcia/webwork/blob/master/lib/Appcia/Webwork/Storage/Config.php#L64
/**
* Merge two arrays recursive
*
* Overwrite values with associative keys
* Append values with integer keys
*
* #param array $arr1 First array
* #param array $arr2 Second array
*
* #return array
*/
public static function merge(array $arr1, array $arr2)
{
if (empty($arr1)) {
return $arr2;
} else if (empty($arr2)) {
return $arr1;
}
foreach ($arr2 as $key => $value) {
if (is_int($key)) {
$arr1[] = $value;
} elseif (is_array($arr2[$key])) {
if (!isset($arr1[$key])) {
$arr1[$key] = array();
}
if (is_int($key)) {
$arr1[] = static::merge($arr1[$key], $value);
} else {
$arr1[$key] = static::merge($arr1[$key], $value);
}
} else {
$arr1[$key] = $value;
}
}
return $arr1;
}
With a little googling I found this:
/**
* jquery style extend, merges arrays (without errors if the passed values are not arrays)
*
* #return array $extended
**/
function extend() {
$args = func_get_args();
$extended = array();
if(is_array($args) && count($args)) {
foreach($args as $array) {
if(is_array($array)) {
$extended = array_merge($extended, $array);
}
}
}
return $extended;
}
extend($defaults, $new_options);
I guess here is the correct answer, because:
your answer have a bug with warning:
Warning: Cannot use a scalar value as an array in...
Because $a is not always an array and you use $a[$k].
array_merge_recursive does indeed merge arrays, but it converts values with duplicate keys to arrays rather than overwriting the value in the first array with the duplicate value in the second array, as array_merge does.
other aswers are not recursives or not simple.
So, here is my answer: your answer without bugs:
function array_extend(array $a, array $b) {
foreach($b as $k=>$v) {
if( is_array($v) ) {
if( !isset($a[$k]) ) {
$a[$k] = $v;
} else {
if( !is_array($a[$k]){
$a[$k]=array();
}
$a[$k] = array_extend($a[$k], $v);
}
} else {
$a[$k] = $v;
}
}
return $a;
}
And my answer with ternary operator:
function array_extend(array $a, array $b){
foreach($b as $k=>$v)
$a[$k] = is_array($v)&&isset($a[$k])?
array_extend(is_array($a[$k])?
$a[$k]:array(),$v):
$v;
return $a;
}
Edit: And a bonus one with as many arrays you want:
function array_extend(){
$args = func_get_args();
while($extended = array_shift($args))
if(is_array($extended))
break;
if(!is_array($extended))
return FALSE;
while($array = array_shift($args)){
if(is_array($array))
foreach($array as $k=>$v)
$extended[$k] = is_array($v)&&isset($extended[$k])?
array_extend(is_array($extended[$k])?
$extended[$k]:array(),$v):
$v;
}
return $extended;
}

Categories