【问题标题】:How to store multiple data for different Keys如何为不同的键存储多个数据
【发布时间】:2016-09-13 10:42:51
【问题描述】:

我有大量数据与每个不同的键相关联。我打算在php中以这种格式存储数据

$item = array(
(
        "key" : key-value;
        "features" : array-of-features;
        "small_images" : array-of-small_images;
    ),

    (
        "key" : key-value;
        "features" : array-of-features;
        "small_images" : array-of-small_images;
    ),

    (
        "key" : key-value;
        "features" : array-of-features;
        "small_images" : array-of-small_images;
    )
);

知道如何创建上述数据结构以及如何在 PHP 中访问其值。如果有其他方法,请务必提及。

编辑:注意这里的数据是array-of-features,array-of-small_images 是一个关联数组,其中包含与主main相同的键和与其值相同的值。

【问题讨论】:

  • 数据库是个不错的选择
  • 使用 JSON 格式 json.org/example.html。您可以使用json_encode() 创建关联数组并转换为 json
  • @xXxpRoGrAmmErxXx 我的基本目的是存储在一个数组中,但问题是这些数据在循环中运行大约 100 次,因此不建议在循环内使用插入查询。所以我想在 $item 这样的数据结构中循环收集数据,然后执行批量插入等操作。
  • @Jigar "我如何创建这样的数据结构" 表示设置为在此结构中存储数据,并且此处所有项目的密钥都是唯一的。
  • 是的,后来知道了,所以删除了我的评论。 @xXxpRoGrAmmErxXx 说的是对的。你不需要每次都在循环中查询,只需在循环中创建一个大查询,然后在循环外执行查询。如果查询太繁重,您甚至可以决定一次插入的数据块。

标签: php arrays multidimensional-array associative-array


【解决方案1】:

如果键是唯一的,则关联数组是理想的解决方案:

$items['key1']['features'] = array-of-features;
$items['key1']['small_images'] = array-of-small_images;

$items['key2']['features'] = array-of-features;
$items['key2']['small_images'] = array-of-small_images;

...

然后,您可以使用 foreach 循环项目:

foreach($items as $key => $item) {
  echo "\n<pre>$key => " . print_r($item, 1) . "</pre>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2018-10-12
    • 2018-04-16
    • 1970-01-01
    • 2021-11-14
    • 2020-02-27
    • 2017-10-10
    相关资源
    最近更新 更多