PHP 1:1到1:很多数组

时间:2014-05-05 12:20:38

标签: php arrays multidimensional-array hashmap associative-array

我有三个名为associativeArray keyArrayvalueArray的数组。 associativeArray是一个由键/值对组成的数组,这些对被拆分并放入keyArrayvalueArray。我现在要做的是创建一个名为newArray的第四个数组,它使用valueArray中的元素作为其键,其值来自各自的keyArray。但与具有1:1键值的associativeArray不同,我希望newArray具有1:多个键值,而没有任何重复键。这是我为它制作的代码:

foreach($keyArray as $keyElement){
    $valueElement = $associativeArray[$keyElement];
    if (!in_array($valueElement,$newArray)){
        array_push($newArray, $valueElement => array($keyElement));
    }
    else{
        array_push($newArray[$valueElement],$keyElement);
    }
}

然而每当我运行它时,我得到:

PHP Parse error:  syntax error, unexpected T_DOUBLE_ARROW

2 个答案:

答案 0 :(得分:1)

您不需要所有这些阵列。只需associativeArray即可。

你可以这样做:

$newArray = array();
// This will loop in the array so that, in each step:
//  - $k is the current key
//  - $v is the current value
foreach($associativeArray as $k => $v) {
    // If newArray doesn't already have $v as a key
    if (!array_key_exists($v, $newArray)) {
        // Define it as a new array with only one element
        $newArray[$v] = array($k);        
    } else {
        // If it already exists, just push $k to it's elements
        $newArray[$v][] = $k; // This is the same as array_push($newArray[$v], $k)
    }
}

答案 1 :(得分:0)

最简单的解决方案可能是这样的

foreach( $keyArray as $key )
{
  // get the value from the associative array
  $value = $associativeArray[ $key ];

  // check if the key was set before into $newArray
  // if you don't check and initialize it, you'll get an error
  // when you try to add new elements
  if( !array_key_exists( $key, $newArray ) )
  {
       $newArray[ $key ] = array();
  }

  // To prevent duplicated ( like you have in your code ) 
  // you just have to check if the element is in the $newArray
  if ( !in_array( $value, $newArray[ $key ] ) )
  {
      $newArray[ $key ][] = $value; // if you wanna use array_push --> array_push( $newArray[ $key ], $value );
  }
}

但是,这取决于你的目标,我会重写使用引用并在数组中转换值的associativeArray。那时你不需要那3个额外的数组,只需要associativeArray和一行代码

// this will cast each value of the array. Since
// the value is referenced the array will be updated.
// You don't have to check for duplicated value because it was an 
// array 'key' => 'val' so it is not possible to have multiple values 
// with the same key
foreach( $associativeArray as $key => &$val )
{
   $val = (array) $val;
}