vendredi 29 mai 2015

Build PHP array with string and result 2 dimensional arrays

I have a smart problem in PHP, I build an array with a string, and at the same time I cut some images. buildProject.php is include in index.php (session_start(); for _session is on the top of it).

buildProject.php

<?php
  $list_projet = array(
    0 => 'img0_pres',
    1 => 'img1_pres',
    2 => 'img2_pres',
  );
  $height_decoup = 500;
  $projet = array();

  foreach ($list_projet as $key => $value) {
    $name_source = $value;
    $img_source_file = 'images/projet/'.$name_source.'.jpg';
    $img_source = imagecreatefromjpeg($img_source_file);

    $width = imagesx($img_source);
    $height = imagesy($img_source);
    $ratio = ceil($height/$height_decoup);
    $img_dest_height = $height_decoup;

    $nb_img_decoup = 1;
    $img_source_y = 0;

    while ($nb_img_decoup <= $ratio) {
      if ($nb_img_decoup == $ratio) {
        $img_dest_height = $height - $height_decoup*($ratio-1);
      }
      $img_dest = imagecreatetruecolor($width,$img_dest_height);
      imagecopy($img_dest, $img_source, 0, 0, 0, $img_source_y, $width, $img_dest_height);
      $img_dest_file = 'images/projet/'.$name_source.'_'.$nb_img_decoup.'.jpg';
      imagejpeg($img_dest, $img_dest_file);

      $projet[$key][$nb_img_decoup] = $img_dest_file; // I SUPPOSE AN ERROR HERE
      $img_source_y += $height_decoup;
      $nb_img_decoup++;
    }
    imagedestroy($img_source);
    imagedestroy($img_dest);
  }
  echo $img_dest_file[0]; // give me an 'i' and suppose give me an error
  echo $projet[0][1][0]; // idem...

  $_SESSION['txt'] = $projet;
?>

After build it, I send it to getProjet.php to find it on main.js with getJSON. My Probleme is, when the array arrived in main.js, projet[0][0] return an ([object, object]).

I thinks the problem is on my first php but I put the other files maybe there are an other error can do that.

getProject.php

<?php
session_start();
$projet = $_SESSION['txt'];

if(isset($_GET['list']) && $_GET['list']>=0){
    echo json_encode($projet[$_GET['list']]);
} ?>

main.js

$.getJSON('php/getProject.php?list=' + index, function(data) {
    length = data.length;
    console.log(data+' //// '+length); // [object object] //// undefined
    console.log(data[1].length); // 29 (total of caracteres...)
    console.log(data[1]); // images/projet/img0_pres_1.jpg
    console.log(data[1][0]); // i
}

So in main.js data=([object object]) and I need data=([object]). I think it's because when i build my array $img_dest_file transform alone in array and it's normaly just a string not an array.

If someone has an idea why $img_dest_file transform alone in array? And I don't want that.

Thanks for reading. If you have question I can specify more.

Aucun commentaire:

Enregistrer un commentaire