如何将关联数组格式化为纯文本中的列和行?

时间:2018-02-16 20:13:08

标签: php associative-array

我有一个看起来像的数组:

extraData

我希望数据采用以下格式:

Array (
 [class_name] => Array ( [0] => 1 [1] => 2 ) 
 [zone1_price] => Array ( [0] => a [1] => s )
 [zone2_price] => Array ( [0] => b [1] => t )
 [zone3_price] => Array ( [0] => c [1] => u )
 [zone4_price] => Array ( [0] => d [1] => v )
)

我试过一个foreach但是无法让它工作,我认为它需要2个或更多foreach,但我正在努力将正确的代码放在一起。< / p>

提前致谢

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的方法,但这些值不会居中:

$array = [
 'class_name' => Array ('1', '2' ),
 'zone1_price' => Array ('a', 's' ),
 'zone2_price' => Array ('b', 't' ),
 'zone3_price' => Array ('c', 'u' ),
 'zone4_price' => Array ('d', 'v' ),
];
echo display_table($array,true);


function display_table($array, $forweb = true) {
    $string = "" ;
    $nl = $forweb ? "<br>" : "\n" ;

    $max=0;
    foreach ($array as $k => $value) {
        $max = max($max,strlen($k));
        $max = max($max,count($value));
    }
    $max+=2;

    if ($forweb) $string .= "<pre>";
    $string .= "| " ;
    foreach ($array as $k => $value) {
        $string .= sprintf("%{$max}s",$k." ")."|";
    }
    $string .= $nl;
    $string .= "+" . str_repeat("-", ($max+1)*count($array)) . "+" ;
    $string .= $nl;
    for ($i=0;$i<count(reset($array));$i++){
        $string .= "| " ;
        foreach ($array as $k => $value) {
            $string .= sprintf("%{$max}s",$value[$i]." ")."|";
        }
        $string .= $nl;
    }
    if ($forweb) $string .= "</pre>";
    return $string ;
}

输出:

|   class_name | zone1_price | zone2_price | zone3_price | zone4_price |
+----------------------------------------------------------------------+
|            1 |           a |           b |           c |           d |
|            2 |           s |           t |           u |           v |

答案 1 :(得分:0)

我不确定我是否清楚地了解了您的要求,但在我看来,您正在寻找类似的内容

public interface SubjectRepository extends JpaRepository<Subject, Long> {

    @Query("select p from Person p where p.hobbyId in ( :hobbyId1, :hobbyId2, :hobbyId3 ")
    List<Person> findByPersonsHobbyId(@Param("hobbyId1") String hobbyId1, @Param("hobbyId2") String hobbyId2, @Param("hobbyId3") String hobbyId3);
}

答案 2 :(得分:-1)

我只知道它,然后只是implode主数组的键,然后来自子数组的implode键0:

echo implode('|', array_keys($array);
echo '<br>';
echo implode('|', array_column($array, 0);