如何从PHP中的数组中按名称选择数据?

时间:2016-06-13 18:56:04

标签: php arrays

我有一个这样的数组:

Array(
    [0]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>k6gIjfO[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [1]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>byUTyJo[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [2]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>oSVEnNk[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [3]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>Dj7GRYS[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [4]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>upsb8IC[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [5]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>YoEEzGi[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [6]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>st3dLNs[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [7]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>LBNpiIG[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [8]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>mFYDmBG[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
    [9]=>Array([uploaderName]=>btknctTR[uploadedImageName]=>z03kSx1[uploaderIp]=>195.155.116.217[uploaderMac]=>e0699587cbfd[uploadedServer]=>alpha)
)

我想从这个数组中获取任何图像的数据。

示例:当用户显示uploadedImageName == jCPjeWv时,我不想知道它是谁的上传者。

3 个答案:

答案 0 :(得分:1)

简单,只需使用foreach

$arr = array(/* content here */);

foreach($arr as $value){
    if($value['uploadedImageName'] == 'jCPjeWv'){
        echo $value['uploaderName'];
        break;
    }
}

答案 1 :(得分:1)

只是为了好玩,这是另一种方式:

echo array_column($array, 'uploaderName', 'uploadedImageName')['jCPjeWv'];
  • 获取一个uploaderName数组,索引设置为uploadedImageName
  • 使用uploadedImageName' jCPjeWv'
  • 访问索引

显然,要多次执行此操作,您可能希望实际创建一个新数组:

$images = array_column($array, 'uploaderName', 'uploadedImageName');
echo $images['jCPjeWv'];

如果您还要访问其他值,请使用null代替uploaderName

$images = array_column($array, null, 'uploadedImageName');
echo $images['jCPjeWv']['uploaderName'];
echo $images['jCPjeWv']['uploaderIp'];

注意:这些方式仅在uploadedImageName唯一时才有效。

答案 2 :(得分:0)

foreach是可能的,但我认为学习数组函数也很重要,所以我将把这个例子放在这里。

$uploadedImageName = 'jCPjeWv';
$filtered = array_filter($array, function($value) use ($uploadedImageName) {
   return ($value['uploadedImageName'] == $uploadedImageName);
});

这将返回$filtered,其他数组已移除,因为$value['uploadedImageName']不等于$uploadedImageName

有关详细信息,请查看http://php.net/manual/en/function.array-filter.php手册。