We help IT Professionals succeed at work.

implode array in php

CalmSoul
CalmSoul asked
on
I have following array ... I am trying to implode it but having difficulties

require 'parserss.class.php'; 
// Second step, create new object 
$ob = new ParseRSS;
$example_ = $ob->parse('http://www.espncricinfo.com/rss/content/feeds/news/6.xml'); 

print_r($example_); 

//echo "'" . implode("','",$example_[items] => Array) . "'";


echo implode(', ', array_map(function ($entry) {
  return $entry['title'];
}, $example_));

Open in new window


I want to get this out put

[title] => BCCI power triangle leaves question mark over control
                    [description] => When the dust had settled on the BCCI elections, one thing was clear: the board would no longer be controlled by one man or group
                    [link] => http://www.espncricinfo.com/india/content/story/842031.html?CMP=OTC-RSS
                    [author] => 
                    [category] => 
                    [comments] => 
                    [enclosure] => 

Open in new window



Array:


Array
(
    [xml_version] => 1.0
    [xml_encoding] => UTF-8
    [rss_version] => 2.0
    [channel] => Array
        (
            [title] => India news from ESPN Cricinfo.com
            [description] => Visit Cricinfo.com for up-to-the-minute cricket news, breaking cricket news, live cricket commentary, ball-by-ball commentary, cricket video, cricket audio and features.
            [link] => http://www.espncricinfo.com
            [copyright] => (c)Cricinfo
            [managingEditor] => 
            [webMaster] => 
            [pubDate] => Mon, 02 Mar 2015 22:27:55 GMT
            [lastBuildDate] => 
            [category] => 
            [generator] => 
            [docs] => 
            [ttl] => 2
            [skipHours] => 
            [skipDays] => 
        )

    [image] => Array
        (
            [title] => India news from ESPN Cricinfo.com
            [description] => 
            [link] => http://www.espncricinfo.com/
            [url] => http://i.imgci.com/espncricinfo/espnci.png
            [width] => 
            [height] => 
        )

    [items] => Array
        (
            [0] => Array
                (
                    [title] => BCCI power triangle leaves question mark over control
                    [description] => When the dust had settled on the BCCI elections, one thing was clear: the board would no longer be controlled by one man or group
                    [link] => http://www.espncricinfo.com/india/content/story/842031.html?CMP=OTC-RSS
                    [author] => 
                    [category] => 
                    [comments] => 
                    [enclosure] => 
                    [guid] => http://www.espncricinfo.com/india/content/story/842031.html
                    [pubDate] => Mon, 02 Mar 2015 22:27:55 GMT
                )

            [1] => Array
                (
                    [title] => BCCI elections to be challenged in court
                    [description] => The BCCI's twice deferred election is set to be challenged in the Bombay High Court on Tuesday over the decision to allow the Baroda Cricket Association president Samarjit Sinh Gaekwad to represent the BCA in the election
                    [link] => http://www.espncricinfo.com/india/content/story/841963.html?CMP=OTC-RSS
                    [author] => 
                    [category] => 
                    [comments] => 
                    [enclosure] => 
                    [guid] => http://www.espncricinfo.com/india/content/story/841963.html
                    [pubDate] => Mon, 02 Mar 2015 15:14:01 GMT
                )

Open in new window

Comment
Watch Question

Commented:
Try:
echo implode(', ', array_map(function ($entry) {
  return $entry['title'];
}, $example_['items']));

or just skip the array_map approach and do it with a simple loop:

$str = "";
foreach($example_['items'] as $entry)
{
  $str .= "," . $entry["title"];
}
$str = substr($str,1);

Commented:
Also, if you're trying to generate a CSV, be mindful to enclose your title with quotes so that any commas in titles won't be interpreted as a delimiter:

e.g. Instead of:
foo,bar,Hello, World!

...do:
"foo","bar","Hello, World!"
Brian TaoOwner
Top Expert 2014

Commented:
a) In your code you were trying to (although it didn't work) implode the "items" element.  In your post you want to output in [key] => value format of the element. So which do you want?  

b) And also please note that "items" itself is actually an array of array.  Do you want to extract only record #0?  Or all records?

c) You only need the fixed sub-items? or you want to be able to programatically list all sub-items no matter what labels/keys there are?

It will be easier for us to help if you tell us the expected resulting output.

Author

Commented:
@gr8gonzo

This worked

echo implode(', ', array_map(function ($entry) {
  return $entry['title'];
}, $example_['items']));

Open in new window

Author

Commented:
Now, the question is how I am going to get following output - using array map


[title] 
[description]
[link] 
[author] 
[category] 
[comments]  
[enclosure]  

Open in new window

Commented:
You can't do that with your current approach if the goal is to implode/concatenate each element. Implode only works on single-dimension arrays. Use the second approach I suggested to gain the extra flexibility.

Author

Commented:
I tried the second approach, but now I am struggling with insert values in MYSQL

Here is what I am doing:

$str = "";
foreach($example_['items'] as $entry)
{
  $str .= "||" . $entry["title"] . "<br><br>" . $entry["description"] . "<br>";
  
  $mysql_values = "'" . $entry["title"] . "'" . "," . "'" . $entry["description"] . "'" . "," . "'" . $entry["link"] . "'" . "," . "'" . $entry["author"] . "'" . "," . "'" . $entry["category"] . "'" . "," . "'" . $entry["comments"] . "'" . "," . "'" . $entry["enclosure"] . "'" . "," . "'" . $entry["guid"] . "'";

		
	$sql =	"INSERT INTO cricrsspak (title,description,link,author,category,comments,enclosure,guid) 
		VALUES ($mysql_values)";
  
  
}
$str = substr($str,1);
echo $str;

Open in new window

Author

Commented:
Just to clear, INSERT statement works but its only inserts one row!!
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Hey CalmSoul,

In the code you've just posted, there is nothing that actually executes a query - you build the query string but do nothing with it. Your code is using the mysql_* functions which are now deprecated, so you should be updating it to use PDO or mySQLi.

Your question was originally about imploding an array, but it looks like that's not what you need. You simply want to loop through an array and insert the records into your database.

Here's some code that show you how to do that using PDO, and a prepared statement:

<?php
// Connect to the database
try {
    $dbh = new PDO('mysql:host=localhost;dbname=yourDatabase', 'username', 'password');
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
    die($e->getMessage());
}

// Prepare a SQL statement
$stmt = $dbh->prepare("INSERT INTO cricrsspak (title, description, link, author, category, comments, enclosure, guid) VALUES (?, ?, ?, ?, ?, ?, ?, ?);");

// Loop through your array
foreach ($example_['items'] as $item):
    // Get rid of the pubDate - we don't need it.
    unset($item['pubDate']);
    // Execute the query
    $stmt->execute(array_values($item));
endforeach;

Open in new window

Author

Commented:
Thanks Chris

I am getting following error:

Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''','','','','','','',''' at line 1' in /home1/xxxx/public_html/xxx/cricinfo_feed.php:91
Stack trace:
#0 cricinfo_feed.php(91): PDOStatement->execute(Array)
#1 {main}

Open in new window


Here is the code:

$mysql_values = "'" . $entry["title"] . "'" . "," . "'" . $entry["description"] . "'" . "," . "'" . $entry["link"] . "'" . "," . "'" . $entry["author"] . "'" . "," . "'" . $entry["category"] . "'" . "," . "'" . $entry["comments"] . "'" . "," . "'" . $entry["enclosure"] . "'" . "," . "'" . $entry["guid"] . "'";


// Prepare a SQL statement
$stmt = $dbh->prepare("INSERT INTO cricrsspak (title, description, link, author, category, comments, enclosure, guid) VALUES" . ($mysql_values) .";" ."");

foreach ($example_['items'] as $item):
    // Get rid of the pubDate - we don't need it.
   // unset($item['pubDate']);
    // Execute the query
    $stmt->execute(array_values($item));
endforeach;

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Have another look at my code - the question marks in the prepared statement are important - they're place holders for the data. You've completely removed them so that's why you get the error.

Also, you need to make sure your $item variable within the foreach loop contains only the data you want in the database and nothing else, which is why I unset the pubDate key. You'll notice there are 8 placeholders matching the 8 fields, so your $item array must contain the data for those 8 fields in the correct order. The first question mark in the prepared statement will automatically get replaced by the first item in the array, the second question mark by the second item, and so on.

Author

Commented:
I think I am confuse now.. so I have add like this

   unset($item['title']);
	unset($item['description']);
	unset($item['link']);
	unset($item['author']);
	unset($item['category']);
	unset($item['comments']);
	unset($item['enclosure']);
	unset($item['guid']);

Open in new window

Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Nope! Given the code you posted earlier, the items in your array contain 9 keys - title, description, link , author, category etc, so when you loop through the array with foreach ($example_['items'] as $item), the $item variable will contain all 9 of those keys. Now you only want to insert 8 of them into your database - all but the pubDate value, so you unset that one (remove it from the array). Your $item array will then contain 8 keys, which are the ones you want to insert into your database - matching the 8 column names with the 8 placeholders.

It may make it easier to visualise if you print out the data you're going to insert into the database using var_dump() - you will see an array containing the 8 'bits' of data that you're about to insert:

foreach ($example_['items'] as $item):
    // Get rid of the pubDate - we don't need it.
    unset($item['pubDate']);
    // Have a look at what will get inserted
    var_dump($item);
    // Execute the query
    $stmt->execute(array_values($item));
endforeach;

Open in new window

Author

Commented:
excellent

Commented:
No shared points for the initial working answer?

Author

Commented:
I am sorry can I change that now ...

Commented:
Thank you!