Jump to content

PHP array from files


wiilweer

Recommended Posts

Hello,

 

I'd like to make an array preferably multidimensional from files what are in subdirectory. Here is a code what I wrote but I doesn't work well becouse I wanted to load that string into javascript array..but it didnt work becouse it had some special characters..

 

$dir = opendir('f');
if($dir)
{
   $result = "";
   while (($file = readdir($dir)) !== false )
   {
      if(strpbrk($file, 'mp3'))
      {
         $result = $result ."{ Track name: \"$file\", location: \"f/$file\" },<br/>";
      }
   }
   echo $result;
   
}

 

Link to comment
Share on other sites

I had similar problem some weeks ago, this should work for you

<?php
function add_dir_data($dir) {
  global $result;
  $d = dir($dir);
  while (false !== ($entry = $d->read())) {
    if ($entry === '.' || $entry === '..') { continue; }
    if (is_dir($entry)) { add_dir_data($entry); }
    elseif (strtolower(substr($entry, -4)) === '.mp3') {
      $result[] = array('track_name'=>utf8_encode(substr($entry, 0, -4)),'location'=>utf8_encode($d->path.'/'.$entry));
    }
  }
  $d->close();
}
$result = array();
add_dir_data('f');
?>
<script type="text/javascript">
var list = <?php echo json_encode($result); ?>;
</script>

 

If you have an outdated version of php(less than 5.2) you probably won't have json_encode, so maybe you can try function __json_encode listed on comments @ http://php.net/manual/en/function.json-encode.php

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.