Domanda

In perl, potrei assegnare un elenco a più valori in un hash, in questo modo:

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

C'è un modo per fare lo stesso in php? In effetti, c'è persino un modo per ottenere una fetta di un array assoc?

È stato utile?

Soluzione

Non esiste un equivalente della sintassi Perl. Ma puoi creare un array di chiavi di interesse e usarlo per cambiare solo una parte dell'array.

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

o

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

Altri suggerimenti

Una semplice riga (alcuni di questi metodi richiedono versioni più recenti di PHP di quelle disponibili al momento della richiesta):

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

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

Voce manuale PHP per array_merge .

Se stai cercando di ottenere un set di chiavi dell'array specifiche, puoi usare questo:

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

Inserimenti manuali in PHP per array_intersect_key e array_fill_keys .

Definisci l'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;

Vedi la funzione list () nel manuale:

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

In breve, no. Tuttavia, è possibile utilizzare una funzione come questa:

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

Modifica: codice modificato nel commento dell'OP di risposta sulla domanda.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top