遍历数组值并在PHP(多维数组)中重新分配

时间:2019-05-28 03:35:03

标签: php arrays codeigniter

"Array
(
  [listing_ticket_name] => ["Early Bird","Late Bird"]
  [listing_ticket_price] => ["1000","500"]
  [listing_ticket_type] => ["2","2"]
  [listing_max_number] => ["1",""]
)

我目前在上面获得数组,但希望将此数组转换为:

$data = array(
 array(
  'listing_ticket_name' => 'Early Bird' ,
  'listing_ticket_price' => '1000' ,
  'listing_ticket_type' => 'My date',
  'listing_max_number' => '1'
),
array(
  'listing_ticket_name' => 'Late Bird' ,
  'listing_ticket_price' => '500' ,
  'listing_ticket_type' => '2',
  'listing_max_number' => ''
 )
);

在数组中循环并合并似乎并不能提供正确的结果。

2 个答案:

答案 0 :(得分:0)

我之所以回答这个问题,是因为我认为重复问题中的答案比其价值更大。这是一个简单的方法:

$a = array(
  'listing_ticket_name' => ["Early Bird","Late Bird"],
  'listing_ticket_price' => ["1000","500"],
  'listing_ticket_type' => ["2","2"],
  'listing_max_number' => ["1",""]
);

foreach ($a as $index => $sub_arr) {

    $i = 0;

    foreach ($sub_arr as $k => $v) {

        $output[$i][$index] = $v;

        $i++;

    }

}

echo '<pre>';

print_r($output);

请注意:与重复答案不同,当阵列不均匀时,这不会失败。

答案 1 :(得分:0)

因此有人帮助指出了正确的方向@Alex(https://stackoverflow.com/users/1482904/alex

我的最终代码有效

filelist = ['file1.csv','file2.csv','file3.csv','file4.csv']
openfiles = []
for filename in filelist:
    openfiles.append(open(filename,'rb'))
masterfile = openfiles.pop(0) 

with (open('output.csv','w')) as outputfile:
    for line in masterfile:
        outputlist = [line.strip()]
        for openfile in openfiles:
            outputlist.append(openfile.readline().strip())
        outputfile.write(str.join(',', outputlist)+'\n')

masterfile.close()
for openfile in openfiles:
    openfile.close()