drvonr6573 2014-05-05 12:20
浏览 34
已采纳

PHP 1:1到1:很多数组

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
  • 写回答

2条回答 默认 最新

  • douchuo1963 2014-05-05 12:36
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程