在php中将数组转换为字典


convert array to dictionary in php

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

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"
        }
    }

即CCD_ 1是CCD_。也许php中有一些函数,这很容易吗?

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);

没有,但您可以用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;
}

您可以使用array_combinearray_column来实现这一点,如下所示:

$result = array_combine(array_column($response, 'id'), $response);

基本上,这个:

  • 提取key0s的值的数组
  • 使用此列表作为新数组的键,使用$response作为值

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

    $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);