I have three arrays called associativeArray
keyArray
and valueArray
. associativeArray
is an array that's made up of key/value pairs, the pairs are split up and placed into keyArray
and valueArray
. What I want to do now is create a fourth array called newArray
that uses the elements in valueArray
as its keys and have the values be from their respective keyArray
. But unlike the associativeArray
that has 1:1 key-to-value, I want to have newArray
have 1:many key-to-value while not having any repeating keys. This is the code I made for it:
foreach($keyArray as $keyElement){
$valueElement = $associativeArray[$keyElement];
if (!in_array($valueElement,$newArray)){
array_push($newArray, $valueElement => array($keyElement));
}
else{
array_push($newArray[$valueElement],$keyElement);
}
}
However whenever I run it I get:
PHP Parse error: syntax error, unexpected T_DOUBLE_ARROW
You don't need all those arrays. Just associativeArray
is enough.
You can do it like this:
$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)
}
}
The simplest solution ever could be something like this
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 );
}
}
But, it depends on your goal, I would rewrite the associativeArray making use of reference and casting the value in an array. At that point you don't need those 3 extra arrays but just associativeArray and one line of code
// 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;
}