我有一个简单的循环问题。 我有这样的数据:
var express = require('express');
var bodyParser = require('body-parser');
var Request = require("request");
var app = express();
app.use(bodyParser.json());
app.post('/building/', function (req, res) {
'use strict';
var myObject = null;
var callSiteApi = {
uri: 'http://localhost:8080/site/',
body: JSON.stringify(req.body),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
// First External API Call
Request(callSiteApi, function (error, response) {
if (error) {
console.log('ERROR with user request.');
return response.sendStatus(500); // Return back that an error occurred
} else {
// Get data from response.body
var materialquerystring = "mat="+response.body.material+"&date="+response.body.date;
var floor = response.body.floor;
for (var i = 0; i < floor.length; i++) {
matereialValueURL = "http://localhost:8080/material/q="+materialquerystring;
// Second External API Call within for loop
Request.get(materialValueURL, (error, response, body) => {
if (error) {
console.log(req.error);
}
materialObject = JSON.parse(body);
var valuequerystring = "value="+materialObject.value;
// do somehting with materialObject
console.log("first request iteration =" + i);
sitevalueURL = "http://localhost:8080/value/q="+valuequerystring;
// Third External API Call within for loop
Request.get(sitevalueURL, (error, response, body) => {
if (error) {
logger.debug('[' + pid + '] ' + req.error);
//return console.dir(error);
}
valueObject = JSON.parse(body);
console.log("second request iteration =" + i);
// do somehting with valueObject 7 materialObject
var a = materialObject.a;
var b = valueObject.b;
var c = a+b;
});
});
}
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end('{"value-1":"a","value-2":"b","value-3":"c","material":"materialquerystring","value":"valuequerystring"}');
}
});
});
我需要创建一个像这样的新表:
$PRODUCT = [
'title' => 'Blouse',
'lines' => [
'variants' => [
[
'price' => 112.34,
'options' => [
'size' => 'small',
'color' => 'yellow',
]
],
[
'price' => 156.33,
'options' => [
'size' => 'small',
'color' => 'blue',
]
],
],
]
我试图在循环中只获取键为$options => [
'size',
'color'
]
的数组,我什至拥有所需的数据,但是我有警告:
'options'
我的循环如下:
Warning: Illegal string offset 'options'
我的错误在哪里?我知道$options = [];
foreach ($PRODUCT['lines'] as $variant){
foreach ($variant as $item) {
$options[] = $item['options'];
}
}
不是数组,但是在这种情况下没有警告怎么办?
答案 0 :(得分:5)
您错过了阵列中的一个关卡。试试这个:
$options = [];
foreach ($PRODUCT['lines']['variants'] as $variant){
foreach ($variant as $item) {
$options[] = $item['options'];
}
}
答案 1 :(得分:3)
您可以使用array_column。
$options = array_column($PRODUCT['lines']['variants'], 'options');
var_dump($options);
Array_column将获取所有名为'options'的数组项,并将其保存到$ options变量中。