如何使用.map将格式的php数组转换为js数组

时间:2019-05-08 09:23:39

标签: javascript php arrays object ecmascript-6

我正在尝试在PHP中获取数组数组,并将其转换为JSON格式的具有新文本格式的javascript数组。在将数组转换为JSON时进行格式更改的最佳实践是什么?

当我将数组引入Javascript时,我尝试使用json_encode ...但这似乎是在创建一个字符串的JS数组,从而使.map返回错误。我可以使.map函数在包含数组硬代码的单个变量上工作。当我将php数组转换为json数组时,无法获取.map来更改格式。我还尝试过一次在MySQL查询中出现一次格式更改结果,但是我尝试的任何方法都没有用。我是JS的新手,所以在数组转换和json重新格式化的详细信息中苦苦挣扎。

var myFences = [];
var jfences = <?php echo json_encode($fences)?>;// puts php array into json formatting into js.
var myFences = Array.from(jfences);

myFences = myFences.map ( e => ({lat: e[0], lng: e[1]}) ) ; 
console.log(myFences); 
var myFences = [$jfences[1]];

let path = jfence; 
path = path.map ( e => ({lat: e[0], lng: e[1]}) ) ; 

php数组的输​​出如下:

Array
(
[0] => [[56.51845972498524, -6.182719791640125],
        [56.52412387806186, -6.18409308265575],
        [56.523103365873006, -6.1784282572162965]]
[1] => [[58.472119674062085, -8.168053780198875],
        [58.47303462652167, -8.161809597612205],
        [58.46960999252895, -8.160264645219627]]
)

但是我需要它是一个json格式的JS数组,其文本更改如下:

var geofence = [
    {lat: 56.51845972498524, lng: -6.182719791640125},
    {lat: 56.52412387806186, lng: -6.175282560388155},
    {lat:56.523103365873006,lng: -6.147215925256319}
];

这是用于生成php数组的代码:

$sql = "SELECT `poly_data` FROM `landowner_polygon` WHERE `landowner_location_id`=".$llocID;

if($result = mysqli_query($link, $sql)){
    if(mysqli_num_rows($result) > 0){

        echo "<table>";
            echo "<tr>";
                echo "<th>poly_data</th>";
            echo "</tr>";
        while($row = mysqli_fetch_array($result)){
            echo "<tr>";
                echo "<td>" . $row['poly_data'] . "</td>";
                $llocFence = $row['poly_data'];
                $allFences = $allFences.$llocFence;
                $fences[] = $llocFence; 
            echo "</tr>";
        }
        echo "</table>";

        // Free result set
        mysqli_free_result($result);
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

// Close connection
mysqli_close($link);


}

5 个答案:

答案 0 :(得分:1)

使用const geoFence = jfences.map((item) => { return item.map(geo => { return { lat: geo[0], log: geo[1] } }) }).flat() 映射数组,并使用.flat()函数展平数组。

const jfences =  [[[56.51845972498524,-6.182719791640125],[56.52412387806186,-6.18409308265575],[56.523103365873006,-6.1784282572162965]],[[58.472119674062085,-8.168053780198875],[58.47303462652167,-8.161809597612205],[58.46960999252895,-8.160264645219627]]]


const geoFence = jfences.map((item) => {
  return item.map(geo => {
    return {
      lat: geo[0],
      log: geo[1]
    }
  })
}).flat();

console.log(geoFence)

.flat()

没有const jfences = [[[56.51845972498524,-6.182719791640125],[56.52412387806186,-6.18409308265575],[56.523103365873006,-6.1784282572162965]],[[58.472119674062085,-8.168053780198875],[58.47303462652167,-8.161809597612205],[58.46960999252895,-8.160264645219627]]] const fencesArrObj = jfences.map((item) => { return item.map(geo => { return { lat: geo[0], log: geo[1] } }) }) const geoFence = [].concat.apply([], fencesArrObj); console.log(geoFence)

public pieChartLabels: Label[] = [['Download', 'Sales'], ['In', 'Store', 'Sales'], 
'Mail Sales'];
public pieChartData: number[] = [300, 500, 100];
public pieChartType: ChartType = 'pie';
  public pieChartOption: any = {
    legend: {
      position: 'right',
      labels: {
        fontSize: 10,
        usePointStyle: true
      }
    }
  }

答案 1 :(得分:0)

这就是我正在使用的:

function jsonObjToArray(jsonObj) {
  var result = [];

    var keys = Object.keys(jsonObj);

    keys.forEach(function (key) {
        result.push(jsonObj[key]);
    });

    return result;
}

我认为这是实现所需需求的快速方法。

答案 2 :(得分:0)

尝试以下代码段

var a = [
  [
    [56.51845972498524, -6.182719791640125],
    [56.52412387806186, -6.18409308265575],
    [56.523103365873006, -6.1784282572162965]
  ],
  [
    [58.472119674062085, -8.168053780198875],
    [58.47303462652167, -8.161809597612205],
    [58.46960999252895, -8.160264645219627]
  ]
]

a = a.map(b => {
  return b.map((c, i) => {
    return {
      lat: c[0],
      lng: c[1]
    }
  })
})

console.log(a)

答案 3 :(得分:0)

这是修改后的代码,它将根据您的要求返回输出。

var myFences = [];
var jfences = <?php echo json_encode($fences)?>;// puts php array into json formatting into js.
jfences.forEach(array => {
    array.map(e => {
        myFences.splice(myFences.length, 0, ({lat: e[0], lng: e[1]}));
    });
}); 
console.log(myFences);


// Output of myFences var
   [
      {"lat": 56.51845972498524,"lng": -6.182719791640125},
      {"lat": 56.52412387806186,"lng": -6.18409308265575},
      {"lat": 56.523103365873006,"lng": -6.1784282572162965},
      {"lat": 58.472119674062085,"lng": -8.168053780198875},
      {"lat": 58.47303462652167,"lng": -8.161809597612205},
      {"lat": 58.46960999252895,"lng": -8.160264645219627}
    ]

或者让我知道您是否还想要其他东西...

答案 4 :(得分:0)

谢谢大家的投入...事实证明,我从PHP出来的数组不是数组,而是看起来像数组的字符串...我想为这个解决方案效劳,但是我我认识一位很棒的建筑师,他给了我一线解决这个问题的方法。你们提供的所有代码都可以正常工作,除了我的原始数组已损坏,因此它不是一个完整的修复程序。这是答案。

var myFences = Array.from(<?php echo json_encode($fences)?>).map(e => eval(e).map(p => ({lat:p[0],lng:p[1]})));

console.log(myFences)

这将返回一个格式正确的数组,我可以使用它来创建正确的输出。