Reputation: 9711
I'm using a DirectoryIterator to get a folder's contents, and it works just fine :
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . $this->certificate), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
array_push($files, $value);
}
unset($value);
But my $files
result when printed it isn't a string but a STD Class. How could I convert that output as a string ( in case there's only one file ) or to an array ?
EDIT : This would be the result I get :
{ [0]=> object(SplFileInfo)#5 (2) { ["pathName":"SplFileInfo":private]=> string(101) "C:\Users\rgr\Apache\htdocs\Roland Groza [ 3.0 ]\class\mongohq/certificate\GTECyberTrustGlobalRoot.crt" ["fileName":"SplFileInfo":private]=> string(27) "GTECyberTrustGlobalRoot.crt" } }
Upvotes: 2
Views: 3221
Reputation: 173642
You can use iterator_to_array()
coupled with array_keys()
.
print_r(array_keys(iterator_to_array($iterator)));
By default, the flags of RecursiveDirectoryIterator
are:
FilesystemIterator::KEY_AS_PATHNAME
FilesystemIterator::CURRENT_AS_FILEINFO
Which uses the current file name as the iterator key and an instance of SplFileInfo
as the iterator value.
Upvotes: 1
Reputation: 11829
$value
is instance of SplFileInfo, if u need filename push $key
or $value->__toString()
to $files
Upvotes: 9
Reputation: 196
You can simply use
array_push((array)$files, $value);
But if $files have multi std class, use Yogesh suggest.
Upvotes: 1
Reputation: 14502
The easiest way would be type casting (more specific array casting):
$foo = new stdClass();
$foo->bar = 'baz';
$foo->boo = 'far';
$arr = (array)$foo;
var_dump($arr);
/*
array(2) {
["bar"]=>
string(3) "baz"
["boo"]=>
string(3) "far"
}
*/
Upvotes: 1
Reputation: 13283
Well, $files
seems to be an array in your example. You are pushing values onto it.
As for converting a stdClass
to array you can convert it by casting:
$obj = new stdClass;
$arr = (array) $obj;
You can also do it the other way around:
$arr = array();
$obj = (object) $arr;
If you want a string out of an object or an array then you need to dereference it:
$str = $arr['key'];
$str = $obj->property;
Does this answer your question or am I misunderstanding you?
Upvotes: 1
Reputation: 30488
use this function to convert from std class object to array
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
// Return array
return $d;
}
}
$arr = objectToArray(files);
print_r($arr);
Upvotes: 1