将多维数组输出为字符串

时间:2018-02-17 20:29:46

标签: php arrays string output

我已经尝试了implode()array_column()和其他几个,但由于某种原因,我无法获得正确的输出显示。

简而言之,如何将此数组作为字符串输出?这实际上是一个输出,它将进入表中的行,这是基于API。

代码:

<td><?php
    $desc1 = file_get_contents("https://api.iextrading.com/1.0/stock/market/batch?symbols=$symbol[$x]&types=news&filter=headline");  
    $desc1 = json_decode($desc1,TRUE); 
    foreach($desc1 as $key111 => $des1) {
        echo ($des1['news']);
    }   
?></td>

给定表格行中var_dump()的示例输出:

  

注意:E:\ XAMPP ...在线(回波线)

中的数组到字符串转换
Arrayarray(1) {
    ["news"]=> array(10) { 
        [0]=> array(1) { 
            ["headline"]=> string(92) "Facebook VP says Russian meddling aimed to divide America and it's working 'incredibly well'"
        } 
        [1]=> array(1) { 
            ["headline"]=> string(66) "In wake of indictments, Facebook doubling security staff to 20,000"
        }

2 个答案:

答案 0 :(得分:1)

每个$ des1中都有一个数组,所以请尝试访问内容,例如:

foreach($desc1['news'] as $key111 => $des1) {
   echo $des1["headline"];
 } 

答案 1 :(得分:1)

您可以使用array_column,如下所示:

$array = [
    "news" => [ 
        [
            "headline" => "Facebook VP says Russian meddling aimed to divide America and it's working 'incredibly well'",
        ],
        [
            "headline" => "In wake of indictments, Facebook doubling security staff to 20,000"
        ]
    ]
];

echo implode(PHP_EOL, array_column($array['news'], 'headline'));

这是the demo

当然,在HTML中,您可以使用<br/>代替PHP_EOL,或者根据您的喜好格式化数据。