1

I am trying to get dir name from my file path: Currently below is my output:

Array
(
    [path] => \documentLibrary\work\marketingProcess\BusinessMarketing\Design\Images\02_Product_Images\04_SHORT-RANGE\NINA\01_NINA-B1\source_WEB
)

and I want to get second last name which is (01_NINA-B1). What I am trying is:

 echo "<pre>".print_r(dirname($results),true)."</pre>"; die;

when I add dirname above it displays nothing. What can I try next?

     $query = db_select('network_drive','networkd');
     $query
    ->fields('networkd', array('path'))
    ->condition('ndid',$networkdriveid,'=')
    ->orderBy('networkd.ndid');
    $results = $query->execute();
    echo "<pre>".print_r(dirname($results['path']),true)."</pre>"; die;
4
  • 1
    If $results is the array above then you need dirname($results['path']) Commented Feb 12, 2020 at 8:00
  • it says: Error: Cannot use object of type DatabaseStatementBase as array in nd_forms_submit() (line 256 of C:\wamp64\www\module_test\modules\nd\nd.module). Commented Feb 12, 2020 at 8:05
  • OK, so $results is not that array. Can you please update your question with what is actually in $results... Commented Feb 12, 2020 at 8:06
  • I have posted a whole code please check my edit question Commented Feb 12, 2020 at 8:07

2 Answers 2

2

This looks like a plain string operation:

  1. split the string
  2. get the desired element

Maybe like this:

$s = '/documentLibrary/work/marketingProcess/BusinessMarketing/Design/Images/02_Product_Images/04_SHORT-RANGE/NINA/01_NINA-B1/source_WEB';

$a = explode(DIRECTORY_SEPARATOR, dirname($s)); //removes source_WEB and splits the string

echo array_pop($a); //gets the last element '01_NINA-B1'

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Is this drupal? from my research I found out that db_select is a drupal function.

Can you try this one? it will attempt to explode the path string and find the second last element, if none is found it will return "N/A"

 $query = db_select('network_drive','networkd');
 $query
->fields('networkd', array('path'))
->condition('ndid',$networkdriveid,'=')
->orderBy('networkd.ndid');
$results = $query->execute();
foreach($results as $result){ 
    $array = explode("\\", $result->path);
    echo isset($array[count($array) - 2]) ? $array[count($array) - 2] : "N/A";
}

1 Comment

It works, thanks. and one more thing if i want to go the path which is before 2nd last then i will do -3?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.