简体   繁体   English

遍历对象数组

[英]Loop through an array with objects

I get the following array from my back end: 我从后端得到以下数组:

[Object { 7="77.105.239.8", 10="77.105.239.11", 18="77.105.239.19", more...}]

How can I use ng-options to fill my select dropdown with the Ips from the array? 如何使用ng-options使用数组中的Ips填充选择下拉列表?

The array above Is the result of an array_diff from my back end In PHP: 上面的数组是后端的array_diff的结果在PHP中:

foreach($ips as $ip)
                {
                    $taken[] = $ip['ip'];
                }

                $start = (ip2long($serie->net) + 1);
                $antal = pow(2,(32-$serie->mask));

                for($i = $start; $i < ($start+$antal-3); $i++)
                {
                    if(end(explode(".", long2ip($i))) != "0")
                    {
                        $possible_ips[] = long2ip($i);
                    }
                }

                $poss = array_diff($possible_ips, $taken);

                return $poss;

Actually you are getting an array with only one field which contains an object with the data you need. 实际上,您得到的数组只有一个字段,其中包含一个包含所需数据的对象。 My suggestion is, to fix that in the backend. 我的建议是,在后端修复该问题。 So that you get what you need -> a real array. 这样您就可以得到所需的内容->一个真正的数组。 Like this: 像这样:

[
     { "id":7, "ip":"77.105.239.8"},
     { "id":10, "ip":"77.105.239.150"}, 
     { "id":12, "ip":"77.105.239.12"}
]

Since array_diff returns an assoziative array, we need to transform it to a non-assoziative array and return it (either with json_encode or not, depending on you set up): 由于array_diff返回一个关联数组,我们需要将其转换为一个非关联数组并返回它(是否使用json_encode,取决于您的设置):

...
$poss = array_diff($possible_ips, $taken);
$res = [];
foreach ($poss as $key => $value) {
    $res[] = $value;
}
return json_encode($res);

If you don't want to or cannot fix the data to be formatted like m4lt3 answer, then you need to do some preprocessing of the data before trying to bind it. 如果您不希望或无法像m4lt3 Answer这样修复要格式化的数据,则需要在对数据进行绑定之前对其进行一些预处理。

var originalData = [{ 7: "77.105.239.8", 10: "77.105.239.11", 18: "77.105.239.19"}];
var originalObject = originalData[0];
var newData = [];
for (var i in originalObject) {
  newData.push({'id': i, 'ip': originalObject[i]});
}
$scope.ipList = newData;

...then you could bind ipList using ngOptions . ...然后您可以使用ngOptions绑定ngOptions

我认为您可以按原样保留函数,除了将return语句更改为: return json_encode($poss);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM