I have two arrays:
$pool = array(
'foo' => array('foobar1'),
'bar' => array('foobar2'),
'lou' => array('foobar3'),
'zuu' => array('foobar4')
);
$remove = array('lou', 'zuu');
How do I get this array:
$result = array(
'foo' => array('foobar1'),
'bar' => array('foobar2')
);
I can do a foreach loop but I like a more elegant solution like
$result = array_intersect_key( $pool, array_flip($remove) );
which gives me the other way:
array(
'lou' => array('foobar3'),
'zuu' => array('foobar4')
);
EDIT: my one line solution is:
array_intersect_key( $pool, array_flip( array_keys( array_diff_key( $pool, array_flip( $remove ) ) ) ) )
try this then
$pool = array(
'foo' => array('foobar1'),
'bar' => array('foobar2'),
'lou' => array('foobar3'),
'zuu' => array('foobar4')
);
$remove = array('lou', 'zuu');
$compare=array_diff_key($pool, array_flip($remove));
var_dump(array_intersect_key($pool,$compare));
Use unset function
unset($pool['lou']);
Related
I have this array:
$flavours = array (
0 => array(799390 => 'Banana',),
1 => array(799391 => 'Chocolate',)
);
And now I inside a foreach looping a set from my database. I get 'Banana' from the database and I need the array to give me 799390.
I have tried:
array_search('Banana', $flavours);
but it does not work unless I add:
array_search('Banana', $flavours[0]);
But I cannot add [0] as I won't be able to tell in which position 'Banana' flavour is in the array.
Any solution apart from looping again inside a foreach??
Thanks a ton
First, we can use array_walk_recursive() to flatten your array, which just gets rid of your nested arrays.
Next, we use array_flip() to swap the keys/values in the flattened array. This makes it easier to grab the ID for a specific term.
<?php
$flavours = [
[799390 => 'Banana'],
[799391 => 'Chocolate']
];
//flatten array
//Produces: Array ( [799390] => Banana [799391] => Chocolate )
array_walk_recursive($flavours,
function($v, $k) use (&$temp) {
$temp[$k] = $v;
}
);
//flip array. Swaps keys with values.
//Produces: Array ( [Banana] => 799390 [Chocolate] => 799391 )
$flavours = array_flip($temp);
Now you can get the ID pretty easily, such as $flavours['Banana'].
If you have a very very large array, this method may become slow. However, I tested this with 100,000 values on my cheap webhost, and ran this method a few times (20-25 times). It is finishing consistently at around (usually under) 0.1 milliseconds, which is about 0.0014 seconds.
You can insert an if statement to set a condition for your loop as
foreach ($flavours as $key => $value) {
if($key = array_search('Banana', $value)){
echo $key;
}
}
Output
799390
If the word being searched for is a different case many of the usual array methods will not work when trying to find the match, using preg_grep however will allow matches to be found in a case-insensitive manner.
function findflavour( $search, $haystack ){
foreach( $haystack as $index => $arr ){
$res=preg_grep( sprintf( '#%s#i', $search ), $arr );
if( !empty( $res ) ) return array_search( array_values( $res )[0], $arr );
}
return false;
}
$search='BaNanA';
$flavours=array(
array( 799390 => 'Banana' ),
array( 799391 => 'Chocolate' ),
array( 729361 => 'Chilli' ),
array( 879695 => 'Apple' ),
array( 995323 => 'Avacado' ),
array( 528362 => 'Orange' ),
array( 723371 => 'Cherry' ),
);
printf( 'Key:%s', findflavour( $search, $flavours ) );
If there might be multiple elements in the source array with the same value but different IDs a slightly different version of the findflavour function
function findflavour( $search, $haystack, $multiple=false ){
$keys=[];
foreach( $haystack as $index => $arr ){
$res=preg_grep( sprintf( '#%s#i', $search ), $arr );
if( !empty( $res ) ) {
$key=array_search( array_values( $res )[0], $arr );
if( $multiple )$keys[]=$key;
else return $key;
}
}
return $multiple ? $keys : false;
}
$multiple=true;
$search='AVacAdo';
$flavours=array(
array( 799390 => 'Banana' ),
array( 799391 => 'Chocolate' ),
array( 291333 => 'Avacado' ),
array( 729361 => 'Chilli' ),
array( 879695 => 'Apple' ),
array( 995323 => 'Avacado' ),
array( 528362 => 'Orange' ),
array( 723371 => 'Cherry' ),
);
printf( 'Key(s): %s', print_r( findflavour( $search, $flavours, $multiple ), true ) );
I'm sure there's a function for this:
What I have:
$myArray = array( 'foo' => 123, 'bar' => 456, 'lou' => 789, 'wuh' => 'xyz' );
$iNeed = array( 'foo', 'lou' );
How can I get the key value pairs that $iNeed:
$output = super_magic_function( $iNeed, $myArray );
// output should be array( 'foo' => 123, 'lou' => 789 );
How is that super_magic_function called (native php if possible)
$output = array_intersect_key($myArray, array_flip($iNeed));
If you need it as a function:
function super_magic_function($array, $required) {
return array_intersect_key($array, array_flip($required));
}
Output:
Array
(
[foo] => 123
[lou] => 789
)
Documentation: array_intersect_key(), array_flip()
Demo.
I have simple array
array(
array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)
How to create associative array by id field (or something else) from it in the right way?
array(
'5' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'20' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'30' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
)
Something along these lines.
$new_array = array();
foreach ($original_array as &$slice)
{
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
#NikitaKuhta, nope. There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading. You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it. I don't like Core Xii's solution as this corrupts the original array as a side effect. I suggest that you don't use references here:
$new_array = array();
foreach ($original_array as $slice) {
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)
I am trying to loop through only a specific sub array in PHP with foreach. Example array:
$testData = array(
$test1=array(
'testname'=>'Test This',
'testaction'=>'create user',
$testData = array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
$anotherArray = array()
),
$test2=array(
'testname'=>'Test That',
'testaction'=>'get user',
$testData = array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
$anotherArray = array()
)
);
And now I am going to go through each test and set some logic based on the name and action, but then need to do several tests on the data. Not sure how to only get $test1's $testData and not $test1's $anotherArray data. I have the following but it doesn't work:
foreach($testData as $test => $section){
foreach($section['testData'] as $field => $value){
\\code
}
}
Any help is appreciated! Thanks!
Try this instead:
$testData = array(
'test1'=>array(
'testname'=>'Test This',
'testaction'=>'create user',
'testData' => array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
'anotherArray' => array()
),
'test2'=>array(
'testname'=>'Test That',
'testaction'=>'get user',
'testData' => array(
'item'=>'value',
'foo'=>'bar',
'xyz'=>'value'
),
'anotherArray' => array()
)
);
I have an array that can vary in how many arrays deep there are, for example:
array(
'one' => array(
array(
'something' => 'value'
),
array(
'something2' => 'value2'
),
'another' => 'anothervalue'
),
'two' => array(
array(
'something' => 'value'
),
array(
'something2' => 'value2'
),
'another' => 'anothervalue'
)
)
Now, let's say I want to replace everything with the key 'something'.
Would I need to use a recursive function to iterate through the array? or is there a better way?
Thank you!
Have a look at array_walk_recursive. It may be quite handy in a situation like this.
Here's an example using array_walk_recursive:
$arr = array(
'one' => array(
array('something' => 'value'),
array('something2' => 'value2'),
'another' => 'anothervalue'
),
'two' => array(
array('something' => 'value'),
array('something2' => 'value2'),
'another' => 'anothervalue'
)
);
function update_something(&$item, $key)
{
if($key == 'something')
$item = 'newValue';
}
array_walk_recursive($arr, 'update_something');
If used inside a class the callback method have to add the object along with the function. This is achieved with an array:
array_walk_recursive($arr, array($this, 'update_something'));
This is a function that you can either be used as a global function or you just put it into a class:
/**
* replace any value in $array specified by $key with $value
*
* #return array array with replaced values
*/
function replace_recursive(Array $array, $key, $value)
{
array_walk_recursive($array, function(&$v, $k) use ($key, $value)
{$k == $key && $v = $value;});
return $array;
}
# usage:
$array = replace_recursive($array, 'something', 'replaced');
It's also making use of array_walk_recursive but encapsulated. The key and the value can be specified as function parameters and not hardencoded in some callback, so it's more flexible.