php - Merging to arrays together -


i trying merge arrays. @ least far know 2 arrays. php returns error saying first not array.

my end goal upload image, existing data in textfile, append new results end of existing data , write database. way doesn't on write file each time new image uploaded , therefore can keep uploading more , more images.

here php:

<?php $sfilename = "imgdb.txt"; $temp = "temp.txt";  for($i=0 ; $i < count($_files) ; $i++){ move_uploaded_file( $_files['file-'.$i]['tmp_name'] , "img/". $_files['file- '.$i]['name'] ); }   // content of file! $simgs = file_get_contents($sfilename); //gets string file. $ajimgs = json_decode($simgs); //converts string array.   $aoutput = array_merge ($ajimgs, $_files);  $asendtofile = json_encode($aoutput, json_pretty_print |  json_unescaped_unicode); file_put_contents($sfilename, $asendtofile); 

the problem here:

$ajimgs = json_decode($simgs); 

by default, json_decode() returns object. if want array can pass boolean true optional second argument:

$ajimgs = json_decode($simgs,1); 

from docs:

assoc

when true, returned objects converted associative arrays.

however, if file "imgdb.txt" empty might boolean false returned json_decode(), can check make sure you've got array this:

$ajimgs = json_decode($simgs,1) ?: array(); 

this shorthand for:

if (json_decode($simgs,1) != false) {     $ajimgs = json_decode($simgs,1); } else {     $ajimgs = array(); } 

update:

to resolve images in json getting overwritten, while still avoiding dupes suggest building new array, using filename key:

// initialize new array use below $files = array(); for($i=0 ; $i < count($_files) ; $i++){     /* reason application posts empty files        without going deep javascript side,        here simple way ignore */     if (empty($_files['file-'.$i]['size'])) continue;      move_uploaded_file( $_files['file-'.$i]['tmp_name'] , "img/". $_files['file-'.$i]['name'] );      // build new array using filenames array keys     $files[$_files['file-'.$i]['name']] = $_files['file-'.$i];      // if don't care dupes can use numeric key     // $files[] = $_files['file-'.$i]; }  // merge new array $aoutput = array_merge ($ajimgs, $files); 

the above has been tested , working me. there's better way handle this, adding files directly decoded json, rewriting entire app beyond scope of question.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -