I would like to do something similar to the following.
$ind=array('a','b','c');
$arr['a']=1;
$arr['b']=4;
$arr['c']=7;
$d= $arr[$ind];
print_r($d);
It obviously doesnt work and I was wondering if there is still a simple way to do it in 1 or two lines of code.
EDIT
Here is a better example to demonstrate what I mean.
$ind=array('a','c','b','d','e','a','a');
$arr['a']=1;
$arr['b']=4;
$arr['c']=7;
$d=$arr[$ind];
Now I want to receive that $d is equal to 1,7,4,1,1
array_intersect_key doesnt work. Or at least I cant make it work for me. I was thinking array_walk and a lamda function or something. Anyone?
NOTE: This syntax is available开发者_运维百科 in Matlab (well, almost). So you could for example type:
arr=rand(20,1);
ind=[1 2 10 2 1 1];
newArr=arr(ind);
and it would produce vector of length 6 with the values as indexed by the ind vector.
To get the items from $arr
which have keys matching the values in $ind
, you can use the following:
$arr = array('a' => 1, 'b' => 4, 'c' => 7);
$ind = array('a','c');
$d = array_intersect_key($arr, array_flip($ind));
// $d = array('a' => 1, 'c' => 7);
The call to array_flip()
simply "flips" the keys/values in $ind
(to make it look like array('a'=>0,'c'=>1)
) then we find the keys intersection with array_intersect_key()
which returns the items from the first array ($arr
) which have keys matching the second array (the flipped $ind
).
Edit Building on mario's answer (which is broken at the time of writing, and doesn't do what you appear to want) you could use
class MultiIndex extends ArrayObject
{
public function offsetGet($offset)
{
if (is_array($offset)) {
$return = array();
foreach ($offset as $o) {
if ($this->offsetExists($o)) {
$return[] = parent::offsetGet($o);
}
}
return $return;
} else {
return parent::offsetGet($offset);
}
}
}
$arr = new MultiIndex($arr);
$d = $arr[$ind];
// $d = array(1,7,4,1,1);
Update: Stealing back from salathe, I've compacted the method to the actually required calls, the $this[$i]
is handled implicitly for existing array keys already. Removed the key capture again.
You can embed the utility code to accomplish this, if you use an array object as workaround:
class MultiIndex extends ArrayObject {
function offsetGet ($keys) {
foreach ($keys as $i) {
isset($this[$i]) and
$r[] = ArrayObject::offsetGet($i);
}
return $r;
}
}
Then transform your array into an object to use the multi-index method:
$arr = new MultiIndex($arr);
$d = $arr[$ind];
This $arr object can still be used with normal assignment or single key queries.
精彩评论