Miomir Dancevic
Miomir Dancevic

Reputation: 6852

Foreach array with different values

Need little help, i get always stupid errors, when i try to do this, i want to foreach array, and inside that do a for loop, is this possible? Here is my code

$image = new SimpleImage();
$slike=array($_FILES['slika1']['tmp_name'],$_FILES['slika2']['tmp_name'],$_FILES['slika3']['tmp_name'],$_FILES['slika4']['tmp_name']);

$koliko = count($slike);

foreach ($slike as $slika) {

    for ($i = 1; $i <= $koliko; $i++)
    {
        $slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
        $image->load($slika);
        $image->resizeToWidth(800);
        $image->save($slicica);
    }
}

I want to get new pictures with this name, example.If last id was 2 i want to get this filenames etc

Still with my code i dont get correct values :( Or maybe there is easy way to do that :)

Upvotes: 1

Views: 190

Answers (3)

take
take

Reputation: 2222

$i=1;
// insert into mysql table..
// [...]
$mysqlId = mysql_insert_id();
foreach ( $_FILES as $key => $value) {

    $slicica="../images/usluge/".$mysqlId."-".$i.".jpg";
    if(move_uploaded_file($_FILES[$key]["tmp_name"],slicica)){ 
        $image->load($slicica);
        $image->resizeToWidth(800);
        $image->save($slicica);
    }
    else {
        // error handling
    }
    $i++;
}

Upvotes: 0

I think what you need is to replace your following line:

$image->load($slika);

for this one:

$image->load($slike[$i-1]);

Upvotes: 1

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5438

you probably have a problem in you foreach as if we do a var_dump on an array we will see the following :

array(3) { [0]=> string(5) "test1" [1]=> string(4) "tes2" [2]=> string(5) "test3" }

so you need to change it to :

foreach ($slike as $key => $slika) {

you can also use move_uploaded_file to achieve what you are trying to do and use linux command convert :

foreach ($slike as $key => $slika) {

    for ($i = 1; $i <= $koliko; $i++)
    {
        $slicica="../images/usluge/".mysql_insert_id()."-".$i.".jpg";
        if(move_uploaded_file(slika,slicica)){ 
            exec("convert $slicica -resize 200 $slicica");
        }else{die('problem loading the file');}

    }
}

Upvotes: 0

Related Questions