我在 PHP 中有一个聪明的问题,我用字符串构建了一个数组,同时我剪切了一些图像。
buildProject.php
包含在 index.php
中(session_start();因为 _session 位于其顶部)。
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;
?>
构建完成后,我将其发送到 getProjet.php
,以便使用 getJSON
在 main.js
上找到它。
我的问题是 $img_dest_file
在数组中单独转换,我需要一个字符串!
我认为问题出在 buildProject.php
上,但我放置了其他文件,也许还有其他错误可以做到这一点。
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 (I need that)
console.log(data[1][0]); // i (But not that, here I want an error)
}
所以在 main.js
data=([object object])
中,我需要 data=([object])
。
我认为这是因为当我运行 buildProject.php
$img_dest_file
在数组中单独转换时,它通常只是一个字符串而不是数组。
如果有人知道为什么 $img_dest_file
在数组中单独转换?
我主要需要的是data.lengh,它实际上是未定义的。
感谢您的阅读。如果您有疑问,我可以详细说明。
最佳答案
我认为,while循环正在迭代,直到“nb_img_decoup”不小于或等于“ratio”。如果该循环对同一“键”迭代多次,那么它将为同一“键”创建多个记录/索引。
这就是为什么当搜索 $projet[$_GET['list']] 时它会返回多个记录,因此返回 [object object]。
关于javascript - 使用字符串和结果二维数组构建 PHP 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30525248/