php - 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;
非常感谢你!
解决方案
您应该生成数据结构,然后通过 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看到它的实际效果
推荐阅读
- excel - 如何根据特定条件找到范围内的最大值?
- abap - SAP Infoset 中的字段不匹配时如何返回值
- c++ - 菊花链函数调用指针
- ios - 带阴影和圆角半径的导航栏
- excel - 连接两个变量名以获得第三个变量的名称
- mysql - 避免在 darby sql 中的 INSERT INTO SELECT 查询中使用 multipal 列重复 NOT Exists 不起作用
- oauth - 如何生成 OAuth1.0 签名
- java - 如何使用 imageview 作为微调器
- javascript - 在javascript中第一次按键后onkeyup不起作用
- php - php日期时间月-1为什么不返回02?