以特定格式输出php数组

时间:2017-07-11 06:07:44

标签: php arrays

我试图以一种格式输出以下数组。它没有得到

package com.idal.cib;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnector {

    static Connection conn1 = null;

    public static Connection getDbConnection(String driver, String url,
            String username, String password) {
        // TODO Auto-generated constructor stub
        try {

            Class.forName(driver);

            conn1 = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn1;
    }

}


package com.idal.cib;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class DBJsonConverter {

    static ArrayList<String> data = new ArrayList<String>();
    static Connection conn = null;
    static PreparedStatement ps = null;
    static ResultSet rs = null;
    static String path = "";
    static String driver="";
    static String url="";
    static String username="";
    static String password="";
    static String query="";

    @SuppressWarnings({ "unchecked" })
    public static void dataLoad(String path) {
        JSONObject obj1 = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        conn = DatabaseConnector.getDbConnection(driver, url, username,
                password);
        try {
            ps = conn.prepareStatement(query);
            rs = ps.executeQuery();
            ArrayList<String> columnNames = new ArrayList<String>();
            if (rs != null) {
                ResultSetMetaData columns = rs.getMetaData();
                int i = 0;
                while (i < columns.getColumnCount()) {
                    i++;
                    columnNames.add(columns.getColumnName(i));
                }
                while (rs.next()) {
                    JSONObject obj = new JSONObject();
                    for (i = 0; i < columnNames.size(); i++) {
                        data.add(rs.getString(columnNames.get(i)));
                        {
                            for (int j = 0; j < data.size(); j++) {
                                if (data.get(j) != null) {
                                    obj.put(columnNames.get(i), data.get(j));
                                }else {
                                    obj.put(columnNames.get(i), "");
                                }
                            }
                        }
                    }

                    jsonArray.add(obj);
                    obj1.put("header", jsonArray);
                    FileWriter file = new FileWriter(path);
                    file.write(obj1.toJSONString());
                    file.flush();
                    file.close();
                }
                ps.close();
            } else {
                JSONObject obj2 = new JSONObject();
                obj2.put(null, null);
                jsonArray.add(obj2);
                obj1.put("header", jsonArray);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    @SuppressWarnings("static-access")
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        driver = "oracle.jdbc.driver.OracleDriver";
        url = "jdbc:oracle:thin:@10.11.34.134:1521:COREMUAT";
        username = "oasisusr";
        password = "p#g_ay0w";
        path = "D:\\VF_Polaris\\968670\\category_list1.json";
        query = "select * from temp_employee";

        DatabaseConnector dc = new DatabaseConnector();
        dc.getDbConnection(driver,url,username,password);
        DBJsonConverter formatter = new DBJsonConverter();
        formatter.dataLoad(path);

    }

}

以上是我的阵列 我希望以下列格式输出 输出:<?php $distance_covered = array( '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)), '2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)), '3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)), '4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)), '5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)), '6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5), 'DRIVER_4' => array(1, 9, 6)), '7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), ); 这是每个驾驶员在所有行程中行驶的距离之和

我试过这样的代码,有人知道请帮助

Array ( [DRIVER_1] => 51, [DRIVER_2] => 33, [DRIVER_3] => 24, [DRIVER_4] => 67, [DRIVER_5] => 34 )

5 个答案:

答案 0 :(得分:1)

这应该有效:

$res = array();
foreach($distance_covered as $value) {
    foreach($value as $key => $number) {
        foreach ($number as $n) {
            if (isset($res[$key])) {
                $res[$key] += $n;
            } else {
                $res[$key] = $n;
            }
        }
    }
}

print_r($res);

答案 1 :(得分:1)

你很亲密,但是......

    $res = array ();

    foreach ( $distance_covered as $value ) {
        foreach ( $value as $key=> $driver ) {
            if ( isset($res[$key]) == false ){
                $res[$key]=0;
            }
            $res[$key] += array_sum($driver);
        }
    }

    print_r($res);

第一个foreach只是简单地将数据拆分为日期。 第二个返回元素,如$ key =&#39; DRIVER_1&#39;和$ driver = array(3,9)。 如果这是您第一次遇到此驱动程序,则需要确保$ res中的元素存在,因此将其设置为0.

一旦你知道那里有一个元素,你可以使用+= array_sum($driver)位添加值的总和(在这种情况下为3和9)。 +=只是添加而不是说a=a+b,您可以说a+=b

答案 2 :(得分:1)

这个适用于我

$res = array();
foreach($distance_covered as $value)//the array which you have given us 
{
    foreach($value as $key => $number) //loop over array of date
    {
        if(!isset($res[$key]))//check if the key exist in over defined array if no then run this
        {
            $res[$key] = array_sum($number);// Sum all distances of that driver
            continue;//set the key and continue the foreach... 
        }
        $res[$key] += array_sum($number);// Sum all distances of that driver    
    }
}

print_r($res);      
die;

输出

Array
(
    [DRIVER_1] => 51
    [DRIVER_2] => 33
    [DRIVER_3] => 24
    [DRIVER_4] => 67
    [DRIVER_5] => 34
)

答案 3 :(得分:1)

只遍历数组数组。

$distance_covered = array(
  '1_JAN_2017' => array('DRIVER_1' => array(2, 5, 3),'DRIVER_2' => array(3, 2, 6, 9)),
  '2_JAN_2017' => array('DRIVER_1' => array(3, 9), 'DRIVER_3' => array(1, 4, 8)),
  '3_JAN_2017' => array('DRIVER_4' => array(9), 'DRIVER_1' => array(2, 7, 5, 2)),
  '4_JAN_2017' => array('DRIVER_1' => array(5, 3, 3, 2), 'DRIVER_4' => array(4, 9, 8, 5)),
  '5_JAN_2017' => array('DRIVER_2' => array(8, 5), 'DRIVER_5' => array(3, 9, 7)),
  '6_JAN_2017' => array('DRIVER_5' => array(2, 1, 7, 5),  'DRIVER_4' => array(1, 9, 6)),
  '7_JAN_2017' => array('DRIVER_4' => array(5, 2, 9), 'DRIVER_3' => array(4, 1, 6)), );

// Counting.
$merged = [];
foreach ($distance_covered as $day => $stats) {
  foreach ($stats as $driver => $distances) {
    if (!isset($merged[$driver])) {
      $merged[$driver] = 0;
    }
    $merged[$driver] += array_sum($distances);
  }
}

// Display.
echo "<pre>";
print_r($merged);
echo "</pre>";

答案 4 :(得分:0)

[讽刺的声音]我不敢相信每个人都忽略了这种复杂的基于函数的单线...

代码:(Demo

var_export(array_map('array_sum', array_merge_recursive(...array_values($distance_covered))));

输出:

array (
  'DRIVER_1' => 51,
  'DRIVER_2' => 33,
  'DRIVER_3' => 24,
  'DRIVER_4' => 67,
  'DRIVER_5' => 34,
)

*实际上,这保证比任何其他发布的答案要慢。

  1. 使用array_values()删除第一级关联键(日期字符串)
  2. 使用“ splat运算符” (...)解开数组的数组,并馈入array_merge_recursive()以对值进行分组
  3. 通过用array_sum()在每个子数组上调用array_map()对子数组值求和

(这只是在框外思考的一种练习。)


除此之外,没有人建议使用空合并运算符,因此我将发布如下内容:

$driver_totals = [];
foreach ($distance_covered as $daily_log) {
    foreach ($daily_log as $driver => $distances) {
        $driver_totals[$driver] = ($driver_totals[$driver] ?? 0) + array_sum($distances);
    }
}
var_export($driver_totals);

如果您有特殊情况,只需要知道一个特定驾驶员的距离,则可以像这样调用array_column()

$target_driver = 'DRIVER_4';
$total_distance = 0;
foreach (array_column($distance_covered, $target_driver) as $distances) {
    $total_distance += array_sum($distances);
}
echo "{$target_driver} drove for a distance of {$total_distance}";

*请注意,每个日期数组中的驱动程序顺序都不重要,因为array_column()足够聪明,可以找到所需的距离子数组。


最后,如果您声明所有可能的驱动程序的白名单数组,则可以:

  • 控制输出中驱动程序的顺序
  • 避免重复的isset()条件
  • 确保输出中没有任何距离记录的驾驶员

代码:

$roster = ['DRIVER_6', 'DRIVER_5', 'DRIVER_4', 'DRIVER_3', 'DRIVER_2', 'DRIVER_1'];
$driver_totals = array_fill_keys($roster, 0);

foreach ($distance_covered as $daily_log) {
    foreach ($daily_log as $driver => $distances) {
        $driver_totals[$driver] += array_sum($distances);
    }
}
var_export($driver_totals);