如何显示数组中的多个特定列并显示为一个字符串

时间:2018-10-12 12:18:49

标签: php laravel

我的数组如下:

 {
        "fileinfo": {
        "database": "homestead",
        "git": "master",
        "date": 12,
        "year": 2018,
        "month": "October"
        }
 }

我想从数组中提取gitBranch,日期,月份,年份并打印为

1个字符串

我尝试过vsprintf和sprintf,但无法弄清楚。

2 个答案:

答案 0 :(得分:3)

假设您将此数组设置为$array

$str = sprintf('Branch: %s, Created: %s %s %s.', 
    $array['fileinfo']['gitBranch'],
    $array['fileinfo']['date'],
    $array['fileinfo']['month'],
    $array['fileinfo']['year']
);

echo $str;

答案 1 :(得分:0)

<?php

$array = array(
    "metadata" => array(),
    "fileinfo" =>array(
        "database" =>"homestead",
        "connection" => "mysql",
        "gitBranch" => "master",
        "minutes" => 41,
        "hours" => 13,
        "date" => 12,
        "year" => 2018,
        "month" => "October"
    )
 );

echo "Branch: {$array['fileinfo']['gitBranch']}, Created: {$array['fileinfo']['date']} {$array['fileinfo']['month']} {$array['fileinfo']['year']}";

这将创建您想要的输出。

对于多个数组,请在内部使用foreach()进行遍历,但是显然$array变量将是您在循环中设置的变量。