douliu1092 2016-10-12 11:56
浏览 37
已采纳

PHP推送关联数组在普通数组中

I have to push an associative array in a normal array (not to convert).
Example (NO CODE):

project = {}
element["title"] = "My title"
element["description"] = "My description"

is there a way to have this

echo $project->title;
//or
echo $project[0]["title"]

? I'v tried this, but server says: ERROR 500

    $i = 0;
    $projects = {};
    foreach($projectsElements as $element) {
        while($i <= $nRowsForProject) {
            $idSection = $element->idSection;
            if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
            else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
            else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
            $i++;
        }
        array_push($projects,$elements);
        $i=0;
    }
  • 写回答

3条回答 默认 最新

  • duanqiao1961 2016-10-12 12:00
    关注

    $projects = {}; is not valid php.

    If you want to initialize an empty array (associative or numeric, that does not matter), you need:

    $projects = [];
    

    or on older php versions:

    $projects = array();
    

    Also note that you need to do the same to your $elements array at the beginning of each iteration otherwise it will grow on every iteration. Assuming that the descriptions are not all the same...

    foreach($projectsElements as $element) {
        $elements = [];
        while($i <= $nRowsForProject) {
            ...
    

    And your while loop does not seem to make a lot of sense: You are not using the $i variable in your loop so are just doing the same assignments on each iteration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案