php - 根据数组中的另一个 id 仅对多数组中的第一项进行排序(PHP)

标签 php arrays

我不知道该怎么做。 请参阅下面的数组。 我在 while 循环中运行这个数组,需要为每个 [topic_id] 找到第一个 [attach_id] 并且可以使用设置的 $topic_id在循环中...

正确的输出应该是:
第一个循环:
[attach_id] => 17989(因为这是 topic_id 20890 的第一个 attach_id)

然后
第二个循环:
[attach_id] => 17896(因为这是 topic_id 20887 的第一个 attach_id)

但是我无法让它工作......

Array ( 
[0] => Array
( 
    [attach_id] => 17989 
    [post_msg_id] => 298566 
    [topic_id] => 20890 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 142437 
    [filetime] => 1442566541 
    [thumbnail] => 1
)
[1] => Array
( 
    [attach_id] => 17990 
    [post_msg_id] => 298566 
    [topic_id] => 20890 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 213432 
    [filetime] => 1442566541 
    [thumbnail] => 1
) 
[2] => Array 
(
    [attach_id] => 17991 
    [post_msg_id] => 298566 
    [topic_id] => 20890 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 63320 
    [filetime] => 1442566541 
    [thumbnail] => 1 
)
[3] => Array
( 
    [attach_id] => 17988 
    [post_msg_id] => 298566 
    [topic_id] => 20890 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 171560 
    [filetime] => 1442566540 
    [thumbnail] => 1
)
[4] => Array
(
    [attach_id] => 17896 
    [post_msg_id] => 298546 
    [topic_id] => 20887 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 304056 
    [filetime] => 1441372805 
    [thumbnail] => 1 
) 
[5] => Array
(
    [attach_id] => 17895 
    [post_msg_id] => 298546 
    [topic_id] => 20887  
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 125938 
    [filetime] => 1441372804 
    [thumbnail] => 1
)
[6] => Array 
(
    [attach_id] => 17894 
    [post_msg_id] => 298546 
    [topic_id] => 20887 
    [extension] => jpg 
    [mimetype] => image/jpeg 
    [filesize] => 328378 
    [filetime] => 1441372785 
    [thumbnail] => 1 
)

)

最佳答案

<?php
$attachTopicId = array();
foreach($array as $subArray) {
    if (array_key_exists($subArray["topic_id"], $attachTopicId)) {
        if ($attachTopicId[$subArray["topic_id"]] < $subArray["attach_id"]) {
            $attachTopicId[$subArray["topic_id"]] = $subArray["attach_id"];
        }
    }
    else {
        $attachTopicId[$subArray["topic_id"]] = $subArray["attach_id"];
    }
}

// test output 
if (count($attachTopicId) > 0) {
    foreach($attachTopicId as $key => $value) {
        print sprintf("Topic ID: %s Attach ID: %s", $key, $value);
    }
}

关于php - 根据数组中的另一个 id 仅对多数组中的第一项进行排序(PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32652651/

相关文章:

javascript - 我怎样才能有一个打印方法,使用 JavaScript

arrays - gfortran 中隐含 do 的数组构造函数的奇怪初始化行为

javascript - 如何展平包含数组的对象数组?

ios - Xcode - 如何将键和值组合成单个数组?

PHP 正则表达式字母数字受非字母数字限制

php - 将表单 POST 提交到另一个页面,但在重定向之前进行验证,如果验证失败,则保留在同一页面上

php - 无法从数据库获取下拉值

php - PHP 是否有内置的 exec ("nslookup"替代品)?

java - 分析从 Java 文件中读取的文本

c数组问题