我构建了一个插件,可以运行CSV文件并将变量解析为自定义帖子的自定义字段。
在我的自定义帖子类型中,我构建了一个带有可重复自定义字段的元框。此元框从MySQL获取数据的格式如下:
a:3:{i:0;a:2:{s:5:"title";s:7:"Title 1";s:5:"point";s:19:"55.635656,12.506767";}i:1;a:2:{s:5:"title";s:7:"Title 2";s:5:"point";s:19:"55.625668,12.502392";}i:2;a:2:{s:5:"title";s:7:"Title 3";s:5:"point";s:19:"55.618781,12.519143";}}
以下代码在CSV文件的x个坐标变量中运行:
// Variables used for getting coordinates
$a = 0;
$b = 0;
$c = 0;
//Variables used for coordinate titles
$ctitle = 0;
// Array containing all imported coordinate sets
$points = array();
//$coordinate;
$Xcoordinate;
$Ycoordinate;
$XYcoordinate;
while (!empty($post["geometry/coordinates/" . $a . "/" . $b . "/" . $c])) {
// Instantiating array that contain a single set of point data
$point = array();
$newctexttitle = \'Title \' . $ctitle;
array_push($point,"title");
array_push($point,$newctexttitle);
array_push($point,"point");
echo "</br>";
echo "Coordinate title is: " . $ctitle;
echo "</br>";
if ($post["geometry/coordinates/" . $a . "/" . $b . "/" . $c]){
echo "The imported X coordinate is: " . $post["geometry/coordinates/" . $a . "/" . $b . "/" . $c];
echo "</br>";
$Xcoordinate = $post["geometry/coordinates/" . $a . "/" . $b . "/" . $c];
// Increase c variable by one
$c++;
echo "C is now: " . $c;
echo "</br>";
}
if ($post["geometry/coordinates/" . $a . "/" . $b . "/" . $c]){
echo "The imported Y coordinate is: " . $post["geometry/coordinates/" . $a . "/" . $b . "/" . $c];
echo "</br>";
$Ycoordinate = $post["geometry/coordinates/" . $a . "/" . $b . "/" . $c];
// Decrease c variable by one
$c--;
echo "C is now: " . $c;
echo "</br>";
}
// Increase b variable by one
$b++;
echo "B is now: " . $b;
echo "</br>";
// Increase title variable by one
$ctitle++;
$XYcoordinate = $Xcoordinate . ", " . $Ycoordinate;
array_push($point,$XYcoordinate);
array_push($points,$point);
// Empty out array for the specific point
unset($point);
}
update_post_meta($post["id"], \'points\', $points);
问题是,post meta以以下格式存储:
a:3:{i:0;a:4:{i:0;s:5:"title";i:1;s:7:"Title 0";i:2;s:5:"point";i:3;s:19:"8.228271, 56.094402";}i:1;a:4:{i:0;s:5:"title";i:1;s:7:"Title 1";i:2;s:5:"point";i:3;s:19:"8.216593, 56.082355";}i:2;a:4:{i:0;s:5:"title";i:1;s:7:"Title 2";i:2;s:5:"point";i:3;s:18:"8.219391, 56.08139";}}
请注意嵌套数组中每个变量的“i:0”、“i:1”、“i:2”等。
为了以相同的格式存储数据,我需要做哪些不同的事情,如上面的示例所示?
SO网友:czerspalace
为了解决这个问题,我在两个数据字符串上都运行了unserialize,并看到顶部的示例保存为关联数组,如:
[title] => Title 1
[point] => 55.635656,12.506767
第二个阵列呈扁平状:
[0] => title
[1] => Title 0
[2] => point
[3] => 8.228271, 56.094402
为了使导入的示例与可重复框匹配,需要替换
array_push($point,"title");
array_push($point,$newctexttitle);
array_push($point,"point");
使用
$point[\'title\'] = $newctexttitle;
和替换
array_push($point,$XYcoordinate);
使用
$point[\'point\'] = $XYcoordinate;