简体   繁体   中英

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?

The array above Is the result of an array_diff from my back end In 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):

...
$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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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