I have problems with arrays. When I try to get the first array [0] it does not give me anything.
This is output
array(4) { [0]=> string(0) "" [333]=> string(123) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/f/de/d6/fded6f1587f863a9e8fc1c2173143a8782fa655e/700Wx700H-105395-0416.jpg" [334]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/e/b9/54/eb954216442547d2ed2c71adbcf73d4f2b3ef903/700Wx700H-105395-a-0416.jpg" [335]=> string(125) "https://s3-us-west-2.amazonaws.com/hl-cdn-prod60/7/16/95/71695917dd17d29648c8f4907000e3c6cab64581/700Wx700H-105395-b-0416.jpg" }
and this is code
private function getImages($dom) {
$images = [];
foreach ($dom->getElementsByTagName('ul') as $ul) {
if ($ul->getAttribute('class') == 'image-thumbnails') {
foreach ($dom->getElementsByTagName('li') as $li) {
$images[] = $li->getAttribute('data-zoom-url');
}
}
}
$images = array_unique($images);
return $images;
}
If you want to exclude empty values, check if the attribute is empty before adding it to the array:
if(!empty($li->getAttribute('data-zoom-url'))) {
$images[] = $li->getAttribute('data-zoom-url');
}
Related
i have string like this
$string = 'root.1.child1.2.nextnode.3.anothernode.4.var';
exploded by "." and created array like this
$arr = array('root','1','child1','2','nextnode','3','anothernode','3','var');
how i can convert this array to something like this ?
it should be dynamically convert because in some cases nodes in string are in a number different with the sample .
["root"]=>
array(1) {
[1]=>
array(1) {
["child1"]=>
array(1) {
[2]=>
array(1) {
["nextnode"]=>
array(1) {
[3]=>
array(1) {
["anothernode"]=>
array(1) {
[3]=>
array(1) {
[var]=>
NULL
}
}
}
}
}
}
}
}
An example using recursive function.
$array = ['root', '1', 'child1', '2', 'nextnode', '3', 'anothernode', '3', 'var'];
function getNestedArray(array $arr, int $idx = 0) {
if ($idx + 1 <= count($arr)) {
return [$arr[$idx] => getNestedArray($arr, $idx + 1)];
}
return null;
}
$output = getNestedArray($array);
var_dump($output);
This can be quit easily achieved by referencing the output and looping over the exploded array:
$output = [];
$reference = &$output;
foreach ($arr as $el) {
if (is_numeric($el)) {
$el = (int)$el;
}
$reference = [];
$reference[$el] = null;
$reference = &$reference[$el];
}
This also checks whether the element is a number and casts it to an integer if it is. The $output variable will contain the final array.
You can use recursive function
to do though
$flatArray = array('root','1','child1','2','nextnode','3','anothernode','3','var'); // your array
function createNestedArray($flatArray)
{
if( sizeof($flatArray) == 1 ) {
return [ $flatArray[0] => null ]; // for the case that paramter has one member we need to return [ somename => null ]
}
$nestedArray[ $flatArray[0] ] = createNestedArray(array_slice($flatArray, 1)); // otherwise we need to call createNestedArray with rest of array
return $nestedArray;
}
$nestedArray = createNestedArray($flatArray); // the result
I'm getting the following array when I upload array of files.
array(1) {
["upload"]=>array(2) {
["name"]=>array(2) {
[0]=>string(9)"file0.txt"
[1]=>string(9)"file1.txt"
}
["type"]=>array(2) {
[0]=>string(10)"text/plain"
[1]=>string(10)"text/html"
}
...
}
}
What is reason (technical reason or any benefits) behind the array received in the above format instead of the following ?
array(1) {
["upload"]=>array(2) {
[0]=>array(2) {
["name"]=>string(9)"file0.txt"
["type"]=>string(10)"text/plain"
...
},
[1]=>array(2) {
["name"]=>string(9)"file1.txt"
["type"]=>string(10)"text/html"
...
}
}
}
I think this is the basic way of how $_FILES provides array now if you want to convert that into the formate you specified i found the code form the link
A nice trick to reorder the $_FILES array when you use a input name as array is:
<?php
function diverse_array($vector) {
$result = array();
foreach($vector as $key1 => $value1)
foreach($value1 as $key2 => $value2)
$result[$key2][$key1] = $value2;
return $result;
}
?>
will transform this:
array(1) {
["upload"]=>array(2) {
["name"]=>array(2) {
[0]=>string(9)"file0.txt"
[1]=>string(9)"file1.txt"
}
["type"]=>array(2) {
[0]=>string(10)"text/plain"
[1]=>string(10)"text/html"
}
}
}
into:
array(1) {
["upload"]=>array(2) {
[0]=>array(2) {
["name"]=>string(9)"file0.txt"
["type"]=>string(10)"text/plain"
},
[1]=>array(2) {
["name"]=>string(9)"file1.txt"
["type"]=>string(10)"text/html"
}
}
}
just do:
<?php $upload = diverse_array($_FILES["upload"]); ?>
$update is a two dimensional associative array. Part of the var_dump is:
array(101) {
[0]=> array(27) { ["code"]=> string(4) "2014" ["na1"]=> string(4) "6010" and many more fields following }
[1]=> array(27) { ["code"]=> string(4) "2015" ["na1"]=> string(4) "6010" and many more fields following }
and many more subarrays following of course . . .
Need to replace the code value with a name and created:
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$val="Name1";
}
elseif ($key=='code' && $val==2015)
{
$val="Name2";
}
}
}
var_dump($update);
The echo $subkey and $val give perfectly the correct values, however de If statement seems never to be true (or is cancelled out again somehow) as the var_dump is leading again to the original values
Some Stackoverflow research even showed constructions with only one foreach loop, much more elegant, but seems not to reach the second array level.
Is there a better approach? Solution to fix this one?
You are not updating the source array.
foreach($update as $key=>$subarray){
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
//$val="Name1";
$update[$key][$subkey] = "Name1" ;
}
elseif ($key=='code' && $val==2015)
{
//$val="Name2";
$update[$key][$subkey] = "Name2" ;
}
}
}
You can access to the field you want by index.
Example :
$i = 0;
$j = 0;
foreach($update as $key=>$subarray){;
foreach ($subarray as $subkey=>$val) {
echo $subkey.$val."<br>";//Just for checking
if ($subkey=='code' && $val==2014)
{
$update[$i][$j] = "Name1";
}
elseif ($key=='code' && $val==2015)
{
$update[$i][$j] = "Name2";
}
$j++
}
$j = 0;
$i++;
}
var_dump($update);
$newArr = array();
foreach($update as $key=>$subarray){
$subNewArr = array();
foreach ($subarray as $item) {
if ($item['code']==2014)
{
$item['code']="Name1";
}
elseif ($item['code']==2015)
{
$item['code']="Name2";
}
array_push($subNewArr, $item);
}
array_push($newArr, $subNewArr);
}
var_dump($update);
Less if else checking
I have an array of JSON objects that look like this:
{"id":1,"place":2,"pic_name":"aaa.jpg"}
My PHP file receives a simple array like:
["4","3","1","2","5"]
These numbers correspond to the place value in my JSON object. Now I need to compare the place of each element in the secont array with the value of ID in the JSON object and if the match I have to replace the value of PLACE with the element from the array.
I am having problems doing the comparison. Any guidelines? What I come up with:
foreach($ids as $index=>$id) { //the array
$id = (int) $id;
foreach ($obj as $key=>$value) { //the JSON objects
foreach ($value as $k=>$v){
if ($id != '' && array_search($index, array_keys($ids)) == $value[$k]['id']) {
$value[$k]['place'] = $id;
file_put_contents($file, json_encode($ids));
} else { print "nope";}
} } }
That will be:
$array = [
'{"id":1,"place":2,"pic_name":"aaa.jpg"}',
'{"id":2,"place":5,"pic_name":"aab.jpg"}',
'{"id":3,"place":1,"pic_name":"aba.jpg"}',
'{"id":4,"place":3,"pic_name":"baa.jpg"}',
'{"id":5,"place":4,"pic_name":"abb.jpg"}'
];
$places = ["4","3","1","2","5"];
$array = array_map(function($item)
{
return json_decode($item, 1);
}, $array);
foreach($array as $i=>$jsonData)
{
if(false!==($place=array_search($jsonData['id'], $places)))
{
$array[$i]['place'] = $place+1;
}
}
$array = array_map('json_encode', $array);
//var_dump($array);
-with output like:
array(5) {
[0]=>
string(39) "{"id":1,"place":3,"pic_name":"aaa.jpg"}"
[1]=>
string(39) "{"id":2,"place":4,"pic_name":"aab.jpg"}"
[2]=>
string(39) "{"id":3,"place":2,"pic_name":"aba.jpg"}"
[3]=>
string(39) "{"id":4,"place":1,"pic_name":"baa.jpg"}"
[4]=>
string(39) "{"id":5,"place":5,"pic_name":"abb.jpg"}"
}
I want to create a file tree, and for this purpose I need to convert an array of files and directories to a multidimensional file tree array. For example:
array
(
'file.txt',
'dir1/',
'dir1/dir2/',
'dir1/dir2/dir3/',
'dir1/file.txt',
)
to
array
(
'file.txt',
'dir1' =>
array
(
'dir2' =>
array
(
'dir3' =>
array(),
),
'file.txt',
)
)
I've tried several functions to accomplish this, but non of them worked. The problem I've encountered for example that there is no easy way to convert an array ('test','test','test'),'test' to $array['test']['test']['test'] = 'test'.
Here's a shorter recursive one:
function dir_tree($dir) {
$files = array_map('basename', glob("$dir/*"));
foreach($files as $file) {
if(is_dir("$dir/$file")) {
$return[$file] = dir_tree("$dir/$file");
} else {
$return[] = $file;
}
}
return $return;
}
Take a look to my post here.
The answer is: strtok will save you.
<?php
$input = [
'/RootFolder/Folder1/File1.doc',
'/RootFolder/Folder1/SubFolder1/File1.txt',
'/RootFolder/Folder1/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/File2.txt',
'/RootFolder/Folder2/SubFolder1/SubSubFolder1/File4.doc',
];
function parseInput($input) {
$result = array();
foreach ($input AS $path) {
$prev = &$result;
$s = strtok($path, '/');
while (($next = strtok('/')) !== false) {
if (!isset($prev[$s])) {
$prev[$s] = array();
}
$prev = &$prev[$s];
$s = $next;
}
$prev[] = $s;
unset($prev);
}
return $result;
}
var_dump(parseInput($input));
Output :
array(1) {
["RootFolder"]=>
array(2) {
["Folder1"]=>
array(2) {
[0]=>
string(9) "File1.doc"
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File1.txt"
[1]=>
string(9) "File2.txt"
}
}
["Folder2"]=>
array(1) {
["SubFolder1"]=>
array(2) {
[0]=>
string(9) "File2.txt"
["SubSubFolder1"]=>
array(1) {
[0]=>
string(9) "File4.doc"
}
}
}
}
}
I have PHP snippet for that:
<?php
function wps_glob($dir) {
foreach (glob($dir . '/*') as $f) {
if(is_dir($f)) {
$r[] = array(basename($f) => wps_glob($f));
}
else {
$r[] = basename($f);
}
}
return $r;
}
function wps_files($path) {
$wpsdir = Array(
'root' => $path,
'struktur' => wps_glob($path)
);
return $wpsdir;
}
?>
example usage here