如何合并两个像这样的数组
$letters = ["A","B","C"];
$words = ["Alpha","Bravo","Charlie"];
放入一系列地图
$result = [
["letter" => "A", "word" => "Alpha"],
["letter" => "B", "word" => "Bravo"],
["letter" => "C", "word" => "Charlie"]];
尽可能高效,整洁地尝试了内置函数,但似乎找不到任何帮助。
答案 0 :(得分:4)
您可以使用array_map
遍历数组,例如:
$letters = ["A","B","C"];
$words = ["Alpha","Bravo","Charlie"];
$result = array_map(function( $letter, $word ){
return [ 'letter' => $letter, 'word' => $word ];
}, $letters, $words);
这将导致:
Array
(
[0] => Array
(
[letter] => A
[word] => Alpha
)
[1] => Array
(
[letter] => B
[word] => Bravo
)
[2] => Array
(
[letter] => C
[word] => Charlie
)
)
答案 1 :(得分:0)
如果您想要单线,
from channels.generic.websocket import AsyncWebsocketConsumer
import json
import asyncio
isconnected = 0
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
print("connect")
await self.accept()
while isconnected == 1:
await asyncio.sleep(2)
print("true")
# obj = # do_something (Ex: constantly query DB...)
await self.send(text_data=json.dumps({
'message': "aaa"
}))
async def disconnect(self, close_code):
# Leave room group
pass
async def receive(self, text_data):
# Receive message from WebSocket
.....
array_map —将回调应用于给定数组的元素
array_combine —通过使用一个数组作为键并使用另一个数组作为其值来创建数组
输出:-
$temp=array_map(function($l,$w){return array_combine(['letter','word'],[$l,$w]);},$letters,$words);
答案 2 :(得分:0)
有一种a1 = -9.9985, -9.9996; a2 = 1.0121, 1.0245; a3 = 12.023, 12.597
方法,但我喜欢这种方法,因为它更加扎根,而且可能更明确(至少对我而言):
array_map()
答案 3 :(得分:0)
Foreach将这样做:
{
"$id": "1",
"innerException": null,
"message": "The feature is disabled. Contact your Azure DevOps Server administrator.",
"typeName": "Microsoft.TeamFoundation.Framework.Server.FeatureDisabledException, Microsoft.TeamFoundation.Framework.Server",
"typeKey": "FeatureDisabledException",
"errorCode": 0,
"eventId": 3000
}
输出:
foreach($letters as $k => $letter)
$output[] = ['letter' => $letter, 'word' => $words[$k]];
var_export($output);