首頁  >  問答  >  主體

PHP 中的陣列:新增條目時的令人驚訝的結果

所以我正在編寫程式碼,允許我收集 Instaloader python 庫收集的圖像,並將它們放入我網站上的圖庫中。我已經設法毫無問題地收集和顯示這些內容,但是我現在已經開始為每篇文章實現標題,但我遇到了問題。

圖書館下載照片的方式是,如果集合中有多於一張照片,它將根據集合中圖像的位置為帖子添加 _1、_2 等後綴,並提供 .txt 文件作為標題。

集合的範例資料夾內容:

2022-12-26_14-14-01_UTC.txt
2022-12-26_14-14-01_UTC_1.jpg
2022-12-26_14-14-01_UTC_2.jpg
2022-12-26_14-14-01_UTC_3.jpg

單一貼文的貼文效果很好 範例:

2022-12-31_18-13-43_UTC.txt
2022-12-31_18-13-43_UTC.jpg

主要程式碼區塊:

$array = []; 
$account_name = "everton";
$file_directory = "images/instagram";
$count = 0;

$hasvideo = 0;
$hasCaption = 0;

$handle = opendir(dirname(realpath(__DIR__)).'/'.$file_directory.'/');
while($file = readdir($handle)){
    $date = substr($file, 0, strpos($file, "_UTC"));
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); // Using strtolower to overcome case sensitive
    if($ext === 'jpg'){
        $count++;

        $collectionSize = (int)str_replace("_", "", str_replace(".jpg", "", explode("UTC",$file)[1]));
        if(!is_numeric($collectionSize)){
            $collectionSize = 0;
        }

        $arrayKey = array_search($date, array_column($array, 'date'));

        if($arrayKey){
            $amount = intval($array[$arrayKey]['collection-size']);
            
            if($collectionSize > $amount){
                $array[$arrayKey]['collection-size'] = (int)$collectionSize;
            }
        }else{
            array_push($array, array ("date" => $date, "collection-size" => (int)$collectionSize, "has-video" => false));
        }
    }
    
    if ($ext === "txt"){
        $file_location = dirname(realpath(__DIR__)).'/'.$file_directory.'/'. $file;
        $myfile = fopen( $file_location, "r") or die("Unable to open file!");
        $caption = fread( $myfile, filesize($file_location));
        $arrayKey = array_search($date, array_column($array, 'date'));

        //$arrayKey returns false when there is a collection. 
        if($array[$arrayKey]){
            $array[$arrayKey]['caption'] = $caption;
        }else{
            array_push($array, array ("date" => $date, "caption" => $caption));
        }
        fclose($myfile);
    }
}

當常規單一貼文上存在集合時,$arrayKey 傳回 false。

我相信這與腳本讀取這些檔案的檔案順序有關,因為我假設它會在讀取 (date)_(collectionposition).jpg 之前讀取 (date).txt

#如果數組條目已經創建,則標題通常會添加到數組資料中,如果沒有(例如存在 _1、_2 等時),則數組不會更新任何內容,也不會引發任何錯誤。

編輯: 進一步的故障排除表明我根據“日期”值更新/檢查數組鍵的方式是錯誤的,希望找到處理這些操作的正確方法

任何有關我可以修復哪些問題以使這項工作按預期進行的指導都將受到讚賞,謝謝!

P粉893457026P粉893457026175 天前398

全部回覆(1)我來回復

  • P粉739942405

    P粉7399424052024-04-01 00:29:12

    讓我們先研究一下你的程式碼。 你提到的問題,即。以下行:

    $arrayKey = array_search($date, array_column($array, 'date'));

    ...傳回 false,因為處理 .txt 檔案時尚未建立帶有日期的 $array 條目。 (使用 array_push 建立陣列成員的邏輯位於程式碼的下方。)

    簡單修復以繼續移動到 if/else 邏輯的相關部分尚未定義

    if($arrayKey !== false && $array[$arrayKey]){
    ...

    也就是說,如果$arrayKey不是false,則繼續將值加入現有陣列成員。否則,建立數組成員。

    此外,處理圖像時有問題,第一次發生時會產生警告:

    $amount = intval($array[$arrayKey]['collection-size']);

    這將會失敗,未定義的陣列鍵「collection-size」,因為 collection-size 鍵尚不存在。修復例如在嘗試對數組鍵進行操作之前,使用空合併運算符設定“預設零”:

    $array[$arrayKey]['collection-size'] ??= 0;

    這些註解修復了錯誤,但是最好將 txt 或 jpg 的第一個實例中的「條目建立」分開 - 使用帶有預期鍵的空數組成員,在執行任何 txt/jpg 特定邏輯之前。我將簡單地使用 $date 本身作為分組,這樣您也可以擺脫 array_search。例如,提取日期後,使用:

    $array[$date] ??= [
        'date' => $date,
        'caption' => '',
        'collection-size' => 0,
        'has-video' => false,
    ];

    然後修改其餘程式碼以符合。 您的程式碼不應依賴檔案讀取的順序。 不保證該順序。否則,您始終可以先將文件列表讀入常規數組,然後對它們進行排序,並在應用特定邏輯時再次迭代。

    簡化的程式碼

    實際需要的程式碼量比您擁有的少很多。這裡我已經為你修剪了。我沒有您的文件,所以這裡有一些虛擬資料:

    $files = <<
    

    您也可以將 glob 檔案放入數組中(= 檔案路徑清單):

    $file_directory = "images/instagram";
    $files = glob(dirname(realpath(__DIR__)).'/'.$file_directory.'/*');

    然後迭代如下:

    foreach($files as $filepath) {
        $filename = basename($filepath);
        $date = strstr($filename, '_UTC', true);
        
        $array[$date] ??= [
            'date' => $date,
            'caption' => '',
            'collection-size' => 0,
            'has-video' => false,
        ];
        
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        
        if($ext === 'jpg'){
            // Each JPG increments collection size:
            $array[$date]['collection-size']++;
        }
        
        elseif ($ext === "txt"){
            // We use a dummy here:
            $caption = '---';
            // $caption = file_get_contents($filepath);
    
            $array[$date]['caption'] = $caption;
        }
    }

    注意它縮小了多少。發生了什麼事?

    • 我們使用 $date 作為陣列的分組索引。不再有 array_search
    • 我們為每個日期初始化一個預設條目。無需進一步檢查或條件!
    • 我們忽略檔案名稱中的 _3 等「集合大小」:只需為每個 JPG 新增 1。
    • 我們使用 nglobfile_get_contents 而不是 readdirfopen
    • 文件的順序並不重要。 (隨意測試和 shuffle($files)!)

    結果:

    array(3) {
        ["2022-12-26_14-14-01"] · array(4) {
            ["date"] · string(19) "2022-12-26_14-14-01"
            ["caption"] · string(3) "---"
            ["collection-size"] · int(3)
            ["has-video"] · bool(false)
        }
        ["2022-12-27_14-14-01"] · array(4) {
            ["date"] · string(19) "2022-12-27_14-14-01"
            ["caption"] · string(3) "---"
            ["collection-size"] · int(2)
            ["has-video"] · bool(false)
        }
        ["2022-12-31_18-13-43"] · array(4) {
            ["date"] · string(19) "2022-12-31_18-13-43"
            ["caption"] · string(3) "---"
            ["collection-size"] · int(1)
            ["has-video"] · bool(false)
        }
    }

    回覆
    0
  • 取消回覆