首页 > 解决方案 > PHP - 如何从多维数组生成非常规数据

问题描述

10 年后我又开始编程了,只是为了好玩。我正在努力使用 PHP 中的以下代码:

这是我从数据库中得到的:

$data[0] = ['id' => NULL, 'titel' => NULL, 'category_id' => NULL];

$data[1] = ['id' => '1', 'titel' => 'Apple', 'category_id' => '123'];
$data[2] = ['id' => '2', 'titel' => 'Pear', 'category_id' => '123'];
$data[3] = ['id' => '3', 'titel' => 'Orange', 'category_id' => '123'];

$data[6] = ['id' => '6', 'titel' => 'Strawberry', 'category_id' => '297'];
$data[7] = ['id' => '7', 'titel' => 'Blueberry', 'category_id' => '297'];
$data[8] = ['id' => '8', 'titel' => 'Raspberry', 'category_id' => '297'];

$data[12] = ['id' => '12', 'titel' => 'Cucumber', 'category_id' => '557'];
$data[13] = ['id' => '13', 'titel' => 'Pumpkin', 'category_id' => '557'];

这是我必须为 javascript 生成的字符串:


'choices': {

    0: {
        text: [''],
        value: ['']
    },
    123: {
        text: ['Apple', 'Pear', 'Orange'],
        value: ['1', '2', '3']
    },
    297: {
        text: ['Strawberry', 'Blueberry', 'Raspberry'],
        value: ['6', '7', '8']
    },
    557: {
        text: ['Cucumber', 'Pumpkin'],
        value: ['12', '13']
    }

}

有人可以帮我解决这个问题吗?我正在尝试这样的事情,但在努力:

  $text = 'text: [';
  $value = 'value: [';
  $final_str = '';
  $current_category_id = '';

  foreach ($data as $foo) {
    if (($foo['category_id'] != $current_category_id)) {
      $text .= ']';
      $value .= ']';
      $final_str .= '}, ' . $product_id . ': { ' . $text . $value;
      $text = 'text: [';
      $value = 'value: [';
    }

    $text .= '\'' . $foo['titel'] . '\', ';
    $value .= '\'' . $foo['id'] . '\', ';
    $current_category_id = $foo['category_id'];
  }
  $text .= ']';
  $value .= ']';
  $final_str .= $current_category_id . ' { ' . $text . $value;

非常感谢你!

标签: phparraysmultidimensional-array

解决方案


您应该生成数据结构,然后通过 json_encode 输出,而不是手动构建字符串:

<?php

$return = [];
foreach($data as $d) {
    $cat_id = intval($d['category_id']);
    
    if (!isset($return[$cat_id])) {
        $return[$cat_id] = [
            'text' => [],
            'value' => [],
        ];
    }
    
    $return[$cat_id]['text'][] = strval($d['titel']);
    $return[$cat_id]['value'][] = strval($d['id']);
}

?>

<script>
    ...
    'choices': <?= json_encode($return); ?>
    ...
</script>

如果你这样做echo json_encode($return);,它将输出:

{"0":{"text":[""],"value":[""]},"123":{"text":["Apple","Pear","Orange"],"value":["1","2","3"]},"297":{"text":["Strawberry","Blueberry","Raspberry"],"value":["6","7","8"]},"557":{"text":["Cucumber","Pumpkin"],"value":["12","13"]}}

您可以在https://3v4l.org/VrHXO看到它的实际效果


推荐阅读