尝试按字母顺序将数组与foreach循环合并。
<?php
$fruits = array(
'Apple' => array('ids'=>array(1,2)),
'Banana' => array('ids'=>array(3,4)),
'Ananas' => array('ids'=>array(5,6))
);
$result = array();
foreach ($fruits as $name=>$subarr) {
$first_letter = mb_substr($name, 0, 1);
$result[$first_letter] = $subarr;
}
的print_r($结果); 给我一些喜欢什么
Array ( [A] => Array ( [ids] => Array ( [0] => 5 [1] => 6 ) )而不是像[B] => Array ( [ids] => Array ( [0] => 3 [1] => 4 ) )
)
那样的smth
{{1}}
我该如何解决?
答案 0 :(得分:1)
您在此行中每次迭代都会覆盖您的结果:
var userAuth = require('./userAuth');
//api list
var apiMiddleware = {
read : {
get : {
},
post : {
'login': userAuth.signin,
}
},
write : {
post : {
'signup' : userAuth.signup,
},
get : {
}
}
}
function Api(type, method,req,res){
this.type = type;
this.method = method;
this.api = api;
this.req = req;
this.res = res;
}
Api.prototype = {
constructor: Api,
init: function() {
var self = this;
//handle get request
console.log(this.type,this.method,this.api);
var apiHandler = ((apiMiddleware[this.type]||{})[this.method] || {})[this.api];
if (apiHandler) {
apiHandler.call(this, this.req);
}
else {
this.notFound();
}
}
}
//all api request will pass through this function
function handleRequest(type, method, api, req, res) {
//to get to pass arguments in api
// var arg = util.objToAry(arguments).slice(2, this.length);
//create apiObject
console.log("in api argument");
var apiObj = new Api(type, method, api, req, res);
// initialize api
apiObj.init();
}
//to export handleRequest
module.exports.handle = handleRequest;
如果结果数组中的subArray不存在,只需创建一个新数组,并将$result[$first_letter] = $subarr;
subArray合并到结果数组中。
ids
答案 1 :(得分:0)
请尝试使用foreach循环。
cout<<Rice.getYear()<<endl;
显示以上代码输出,如下所示。
$fruits = array(
'Apple' => array('ids'=>array(1,2)),
'Banana' => array('ids'=>array(3,4)),
'Ananas' => array('ids'=>array(5,6))
);
$result = array();
foreach ($fruits as $name=>$subarr) {
$first_letter = mb_substr($name, 0, 1);
foreach($subarr as $key=>$value){
foreach ($value as $gkey => $gvalue) {
$result[$first_letter]['ids'][] = $gvalue;
}
}
}
echo "<pre>";
print_r($result);