将字符串存储到数组中

时间:2018-10-08 08:33:22

标签: mysql laravel

在MySQL中,我有一个字段名邮政编码,类型为LONGTEXT。它存储几个用逗号分隔的邮政编码。我将如何检索并将其存储为数组以供其他使用?

4 个答案:

答案 0 :(得分:0)

将其存储为MySQL中的JSON字段,当分别检索和保存它们时,Laravel对其进行编码和解码

在迁移中

$table->json('field_name');

然后在模型中

protected $json = ['field_name'];

然后,只要您访问该字段,laravel就会为您将其转换为数组,您无需调用任何显式方法。

文档-https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting

答案 1 :(得分:0)

您可以使用PHP方法 atlTraceUtil - Warning: dialog creation failed, so application is terminating unexpectedly. atlTraceUtil - Warning: if you are using MFC controls on the dialog, you cannot #define _AFX_NO_MFC_CONTROLS_IN_DIALOGS. The thread 0x3a58 has exited with code 0 (0x0). The thread 0x3d58 has exited with code 0 (0x0). The thread 0x22a8 has exited with code 0 (0x0). The program '[14088] MFCApplication6.exe' has exited with code 0 (0x0).

您认为做不到的是在数据库中对其进行explode()

在模型中,您可以设置mutator方法:

where x = x

答案 2 :(得分:0)

让我们说您将结果存储在这样的字符串中:

$s = "6000,5447"; //$s = $array->postcodes;

您可以使用以下方法获取数组索引中的每个值:

$values= explode(",", $s);
echo $values[0]; // 6000

甚至更好..您可以将其存储为json,并以数组格式将其检索为json。

答案 3 :(得分:0)

// the final array all the post codes are collected.
$postCodes = [];

foreach (Model::pluck('postcodes') as $stringCodes)
    foreach (explode(',', $stringCodes) as $postCode) $postCodes[] = $postCode;