Question

En perl, je pouvais attribuer une liste à plusieurs valeurs dans un hachage, comme suit:

# 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 );

Y at-il un moyen de faire la même chose en php? En fait, y a-t-il même un moyen d'obtenir une tranche d'un tableau d'assoc?

Était-ce utile?

La solution

Il n’existe pas d’équivalent à la syntaxe Perl. Mais vous pouvez créer un tableau des clés d’intérêt et l’utiliser pour ne modifier qu’une partie de votre tableau.

$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

Autres conseils

Une ligne simple (certaines de ces méthodes nécessitent des versions de PHP plus récentes que celles disponibles au moment de la demande):

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

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

Entrée manuelle dans PHP pour array_merge .

Si vous souhaitez obtenir un ensemble de clés de tableau spécifiques, vous pouvez utiliser ceci:

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

Entrées du manuel PHP pour array_intersect_key et array_fill_keys .

Définissez le hachage:

$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;

Voir la fonction list () dans le manuel:

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

En bref, non. Cependant, vous pouvez utiliser une fonction comme celle-ci:

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));

Éditer: code ajusté dans la réponse du commentaire de l'OP à la question.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top