1

My array looks like this:

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

I want to pickup gitBranch, date, month, year from the array and print as

1 string

I tried vsprintf and sprintf, but cannot figured out.

CH_user303
  • 67
  • 1
  • 11

2 Answers2

3

Assuming you have this array as $array

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

echo $str;
sietse85
  • 1,488
  • 1
  • 10
  • 26
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']}";

This creates the output you desire.

For multiple arrays, do a foreach() through them with that inside, but obviously the $array variable will be whatever you set it to in the loop.

Adam
  • 1,294
  • 11
  • 24
  • 1
    I liked the idea how @sietse85 used sprintf to combined them. but thx anyway – CH_user303 Oct 12 '18 at 12:36
  • I also like it muchly! Will have to try and use it in future! – Adam Oct 12 '18 at 15:35
  • Also, might be worth you checking this out just for a more complete understanding of both solutions: https://stackoverflow.com/questions/7147305/performance-of-variable-expansion-vs-sprintf-in-php which also links to this: http://judebert.com/progress/archives/204-PHP-String-Formatting-Performance.html which is all about PHP String Formatting Performance – Adam Oct 12 '18 at 15:38