atribuir a uma fatia de matriz associativa em php
-
10-07-2019 - |
Pergunta
Em perl, eu poderia atribuir uma lista de vários valores em um hash, assim:
# 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 );
Existe alguma maneira de fazer o mesmo em php? De fato, há mesmo uma maneira de obter uma fatia de uma matriz assoc em tudo?
Solução
Não há equivalente à sintaxe Perl. Mas você pode fazer uma série de teclas de interesse e usar isso para alterar apenas parte de sua matriz.
$koi=array('foo', 'bar', 'baz' );
foreach($koi as $k){
$myarr[$k]++; //or whatever
}
ou
array_walk($myarr, create_function('&$v,$k','$v=(in_array($k,$koi))? $v*2 : $v;')); //you'd have to define $koi inside the function
Outras dicas
Um simples one-liner (alguns destes métodos requerem versões mais recentes do PHP que estavam disponíveis no momento de pedir):
$hash = array(
'foo'=>1,
'bar'=>2,
'baz'=>3,
);
$hash = array_merge( $hash, array( 'foo' => 4, 'bar' => 4, 'baz' => 5 ) );
PHP entrada manual para array_merge .
Se você estiver olhando para obter um conjunto de chaves de matriz específicos, você pode usar isto:
$subset = array_intersect_key( $hash, array_fill_keys( array( 'foo', 'baz' ), '' ) );
PHP entradas manuais para array_intersect_key array_fill_keys .
Definir o hash:
$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;
Veja a função list () no manual:
Em suma, não. No entanto, você poderia usar uma função como esta:
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));
Edit:. Código ajustado no comentário de OP resposta em questão