如何使用PHP将数组排序为特定格式

时间:2017-06-26 08:58:36

标签: php arrays

我需要一个帮助。我需要使用PHP将数组排序为特定格式。我在下面解释我的代码。

$firstArr=array("K"=>"location","L"=>"nearaddrss","M"=>"dsdsfll");
$secondArr=array(array("K"=>"loc","L"=>"Aggggkk","M"=>"dsdsfuu","A"=>"jhkhjg","B"=>"nnnn","C"=>"dsmmmmdsf"),array("K"=>"lo","L"=>"Aggggpp","M"=>"dsdsfjj","A"=>"jhkhjg","B"=>"nnnn","C"=>"dsmmmmdsf"));
$firstResultArr=array();
$secondResultArr=array();
foreach ($firstArr as $key => $value) {
    foreach ($secondArr as $key1 => $value1) {
        foreach ($value1 as $key2 => $value2) {
            if($key==$key2){
                $firstResultArr[]=$value;
                $secondResultArr[]=array($value=>$value2);
            }
        }
    }
}
echo json_encode($secondResultArr);exit;

这里我以下面的格式获得输出。

[{"location":"loc"},{"location":"lo"},{"nearaddrss":"Aggggkk"},{"nearaddrss":"Aggggpp"},{"dsdsfll":"dsdsfuu"},{"dsdsfll":"dsdsfjj"}]

但是我需要输出如下所示。

[{"location":"loc","nearaddrss":"Aggggkk","dsdsfll":"dsdsfuu"},{"location":"lo","nearaddrss":"Aggggpp","dsdsfll":"dsdsfjj"}]

请帮帮我。

2 个答案:

答案 0 :(得分:0)

迭代第二个数组,并在其中迭代第一个数组。

<?php
$firstArr=array(
        "K"=>"location",
        "L"=>"nearaddrss",
        "M"=>"dsdsfll"
);

$secondArr=array(
        array(
            "K"=>"loc",
            "L"=>"Aggggkk",
            "M"=>"dsdsfuu",
            "A"=>"jhkhjg",
            "B"=>"nnnn",
            "C"=>"dsmmmmdsf"
        )
        ,array(
                "K"=>"lo",
                "L"=>"Aggggpp",
                "M"=>"dsdsfjj",
                "A"=>"jhkhjg",
                "B"=>"nnnn",
                "C"=>"dsmmmmdsf")
        );

$result = array();

foreach ($secondArr as $key2 => $value2) {
    $item = array();
    foreach ($firstArr as $key => $value) {
        $item[$value] = $value2[$key];
    }
    $result[] = $item;
}

echo json_encode($result);
die();

答案 1 :(得分:0)

看一看。

import time,os,urllib2
coun=input("Enter count of the movies:")
x=0
namelist=[]
addresslist=[]
os.chdir('D:\\')
while(coun > x):
    name=raw_input("Enter the name of movie:")
    namelist.append(name)
    address=raw_input("enter the address of %s:"%(name))
    addresslist.append(address)
    x=x+1
ti= time.localtime().tm_hour
print('it\'s wating...')
while(ti!=11):
    ti= time.localtime().tm_hour
    timi=time.localtime().tm_min
    tisec=time.localtime().tm_sec
    if (ti==3 & timi==59 & tisec==59):
        print('it\'s 3')
print('it\'s your time.let start downloating')
x=0
while(coun > x):
    data=urllib2.urlopen(address[x])
    file=open(namelist[x],'wb')
    file.write(data)
    file.close()
    x=x+1