在PHP中将值分配给关联数组切片

4
在Perl中,我可以将一个列表分配给哈希表中的多个值,如下所示:
# define the hash...
my %hash = (
  foo => 1,
  bar => 2,
  baz => 3,
);

# change foo, bar, and baz to 4, 5, and 6 respectively
@hash{ 'foo', 'bar', 'baz' } = ( 4, 5, 6 );

在PHP中是否有类似的方法?事实上,是否存在一种获取关联数组片段的方法?


注意:我已经知道列表,问题的重点是找到比以下更优雅的解决方案: list($array['a'], $array['b'], $array['c'], $array['d'], $array['e'], $array['f'], $array['g'], $array['h'], $array['i'], $array['j'], $array['k'], $array['l'], $array['m']) = some_function(); - Stephen Sorensen
4个回答

3

一个简单的一行代码(某些方法需要比提问时还不可用的新版本PHP):

$hash = array(
    'foo'=>1,
    'bar'=>2,
    'baz'=>3,
);

$hash = array_merge( $hash, array( 'foo' => 4, 'bar' => 4, 'baz' => 5 ) );

PHP手册中array_merge的条目。

如果你想获取一组特定的数组键,可以使用以下方法:

$subset = array_intersect_key( $hash, array_fill_keys( array( 'foo', 'baz' ), '' ) );

PHP手册中的array_intersect_keyarray_fill_keys条目。


1

定义哈希:

$hash = array(
  'foo' => 1,
  'bar' => 2,
  'baz' => 3,
);

# change foo, bar, and baz to 4, 5, and 6 respectively
list($hash['foo'], $hash['bar'], $hash['baz']) = array( 4, 5, 6 );

# or change one by one
$hash['foo'] = 1;
$hash['bar'] = 2;
$hash['baz'] = 3;

看一下手册中的list()函数。

http://php.net/manual/en/function.list.php


list() 的作用与常规相反:它接受一个变量列表和一个数组,将数组中的每个项目分配给相应的变量(即它是一种从数组中取出东西而不是放入东西的方法)。 - Jacob Mattison
你可以这样做 $info = array(4,5,6); list($a['foo'], $a['bar'], $a['baz']) = $info; 但在那里使用 "list" 真的没有什么用处。 - Jacob Mattison
这种方法是可行的,但它正是我试图避免的。我不想为每个键入关联数组的名称。像“assoc_array_slice($array,'foo','bar','baz')= array(4,5,6)”这样的东西才是我真正需要的。 - Stephen Sorensen
是的,但在PHP中没有与给定示例完全对应的1对1等效项,我尝试找到最接近的。 - Emre Yazici

0

没有与Perl语法相当的东西。但是你可以创建一个感兴趣的键数组,并使用它来仅更改数组的一部分。

$koi=array('foo', 'bar', 'baz' );
foreach($koi as $k){
  $myarr[$k]++; //or whatever
}

或者

array_walk($myarr, create_function('&$v,$k','$v=(in_array($k,$koi))? $v*2 : $v;')); //you'd have to define $koi inside the function

0
简而言之,不行。但是,您可以使用类似于这样的函数:
function assignSlice($ar,$keys,$args) {
  if (count($keys) !== count($args)) {
    // may want to handle more gracefully;
    // simply returns original if numbers of keys and values
    // don't match
    return $ar;
  }                                                 
  foreach ($keys as $index=>$key) {
    $ar[$key] = $args[$index];
  }
  return $ar;
}

$test = array(
    'foo'=>1,
    'bar'=>2,
    'baz'=>3,
    );

$newtest = assignSlice($test,array('foo','bar'),array(4,5));

编辑:根据楼主在问题下的评论调整了代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接