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.

5
  • Add your attempts to your question. There should be nothing difficult about concatenating strings together. Commented Oct 12, 2018 at 12:19
  • Try to json_decode it, that will result in an array of the data Commented Oct 12, 2018 at 12:19
  • @KoenHollander, I dont want an array. Its already an array. I want specific keys and values in one string. Commented Oct 12, 2018 at 12:21
  • @JonStirling The difficult part is not all the array but only specific columns Commented Oct 12, 2018 at 12:22
  • Pulling specific names key values shouldn't be difficult either, so again please add your attempted code. Commented Oct 12, 2018 at 12:25

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I liked the idea how @sietse85 used sprintf to combined them. but thx anyway
I also like it muchly! Will have to try and use it in future!
Also, might be worth you checking this out just for a more complete understanding of both solutions: stackoverflow.com/questions/7147305/… which also links to this: judebert.com/progress/archives/… which is all about PHP String Formatting Performance

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.