【问题标题】:convert array to dictionary in php在php中将数组转换为字典
【发布时间】:2015-05-05 13:01:30
【问题描述】:

我有数组(从数据库返回),看起来像这样:

response = {
    0 = {
        id = "12312132",
        title = "title1",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    1 = {
        id = "456456456",
        title = "title2",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    2 = {
        id = "789789789",
        title = "title3",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    }

我需要像这样在字典中使用 php 转换它:

response = {
    "12312132" = {
        title = "title1",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    "456456456" = {
        title = "title2",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    "789789789" = {
        title = "title3",
        ....
        createDT = "2015-03-03 22:53:17"
        }
    }

keyid。或许php中有一些函数,方便吗?

【问题讨论】:

    标签: php arrays dictionary


    【解决方案1】:

    PHP 中没有 dictionary 术语。您的实际意思是associative array,通常也称为hash。虽然同样的事情,但这可以使将来更容易在谷歌上搜索。

    你可以有几种方法,我给你经典的foreach()一个。 我认为array_map() 的方法也是可能的。

    $response = ...;        // your database response
    $converted = array();   // declaring some clean array, just to be sure
    
    foreach ($response as $row) {
        $converted[$row['id']] = $row;        // entire row (for example $response[1]) is copied 
        unset($converted[$row['id']]['id']);  // deleting element with key 'id' as we don't need it anymore inside
    }
    print_r($converted);
    

    【讨论】:

    • array_map 的问题是它不能在按键上工作。无论如何,foreach 循环通常更快。
    • @Niols 谢谢,我不确定。我不是array_maparray_walk 的忠实粉丝,对它们一无所知。
    • array_walk (stackoverflow.com/questions/13036160/…) 可能会实现。但是,是的,这不是一个有效的代码。
    【解决方案2】:

    不,但是你可以用 PHP 写一个小程序:

    $result = array();
    foreach ($response as $row)
    {
      $id = $row['id'];
      unset($row['id']);
      $result[$id] = $row;
    }
    
    echo '<pre>';
    print_r($result);
    echo '</pre>';
    

    甚至把它变成你自己的函数:

    function dictonary($response) 
    {
      $result = array();
      foreach ($response as $row)
      { 
        $id = $row['id'];
        unset($row['id']);
        $result[$id] = $row;
      }
      return $result;
    }
    

    【讨论】:

    • 在那个循环之前$result = array();
    • @n-dru:是的,初始化是个好习惯。我会添加它。谢谢。
    【解决方案3】:

    循环遍历结果以再次以新格式填充数组

        $count = count($response) // count the items of your initial array
        $i=0;
        while($i<$count) { //start a loop to populate new array
        $key = $response[i]['id'];
        $new_response[$key] = array('title' =>  $response[i]['title'], ... ,'createDT' => $response[i]['createDT']);
        $i++;
        } // end loop
    
    print_r($new_response);
    

    【讨论】:

    • 请不要只发布代码而不解释我们正在查看的内容。
    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 2017-07-21
    • 2021-08-10
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2013-05-26
    • 2010-09-16
    相关资源
    最近更新 更多