简体   繁体   English

从复杂的 php 数组打印表格或列表

[英]Printing a table or list from a complex php array

I have an array that is generated from a third party.我有一个由第三方生成的数组。 Which means I must work with the array format I have been given.这意味着我必须使用我得到的数组格式。 Below is an array extract from var_dump.下面是从 var_dump 中提取的数组。

{ 
    [0]=> object(stdClass)#3510 (3) { 
        ["privacy"]=> string(1) "0" 
        ["name"]=> string(11) "jumpsuits" 
        ["token"]=> string(12) "PD21B62AIFFM" 
    } 
    [1]=> object(stdClass)#3509 (3) { 
        ["privacy"]=> string(1) "1" 
        ["name"]=> string(8) "helmets" 
        ["token"]=> string(12) "PL68C79RKYAP" 
    } 
} 

I am not a php programmer.我不是 php 程序员。 But I do need to find a simple way in PHP to turn the array data in the format above into a three column table with the headings 'privacy', 'name' and 'token'.但我确实需要在 PHP 中找到一种简单的方法,将上述格式的数组数据转换为一个三列表,标题为“隐私”、“名称”和“令牌”。

If I could just get a starter for ten as to why echo $array['name'][0] returns nothing I think I could work the rest out.如果我能得到一个关于为什么echo $array['name'][0]什么都不返回的 10 的入门,我想我可以解决 rest。

Thank you谢谢

    <?php    
        $array = json_decode(json_encode($object), true); // convert array of object to assoc array
        //all array:
        var_dump(array_column($array, 'privacy')); //privacy as array
        var_dump(array_column($array, 'name')); //name as array
        var_dump(array_column($array, 'token')); //token'
        //specific data:
        $data['privacy'] = array_column($array, 'privacy');
        $data['name'] = array_column($array, 'name');
        $data['token'] = array_column($array, 'token');
        
        echo $data['name'][0];
        //etc

Is an array of objects, so you can loop it like this;是一个对象数组,所以你可以像这样循环它;

<?php
echo '<table>';
echo '<tr>';
echo '<td>';
echo 'Privacy';
echo '</td>';
echo '<td>';
echo 'Name';
echo '</td>';
echo '<td>';
echo 'Token';
echo '</td>';
echo '<tr>';
foreach($data as $row) {
    echo '<tr>';
    echo '<td>';
    echo $row->privacy;
    echo '</td>';
    echo '<td>';
    echo $row->name;
    echo '</td>';
    echo '<td>';
    echo $row->token;
    echo '</td>';
    echo '<tr>';    
}
echo '</table>';

Check it in codepad http://codepad.org/MhcaKKRP在键盘上查看http://codepad.org/MhcaKKRP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM