[英]fetch specific value from an array
我有一个来自这段代码的数组
echo "<pre>";
print_r($_SESSION["followers"]);
echo "</pre>";
数组是
Array
(
[pagination] => Array
(
)
[meta] => Array
(
[code] => 200
)
[data] => Array
(
[0] => Array
(
[username] => SD
[profile_picture] => https://instagramimages-a.akamaihd.net/profiles/profile_4.jpg
[id] => 42114932
[full_name] => A
)
[1] => Array
(
[username] => ER
[profile_picture] => https://igcdn-photos-c-a.akamaihd.net/hphotos-ak-xpf1/t51.2885-19/1.jpg
[id] => 395834289
[full_name] => P
)
)
)
我想知道是否有可能匹配数组中的特定值,然后获取与其相关的其他值,
例如,我正在获得id = 42114932的值,现在我希望在给定数组中匹配此值以及它匹配的任何地方,我希望获取该id的用户名,全名和个人资料照片,在这种情况下对应于id 42114932我希望要得到
username=SD,
full_nmae=A
profile_pic = https://instagramimages-a.akamaihd.net/profiles/profile_4.jpg
如果有可能,任何人都可以告诉它是如何做到的
一个选项是循环通过数组
$f = ..; //(the id to find)
for($i = 0, $i < count($data); i++)
{
if($data[$i]['id'] == $f){
echo 'Full name : '.$data[$i]['fullname'];
echo '<br />Username : '.$data[$i]['username'];
echo '<br />Profile picture : '.$data[$i]['profile_pic'];
}
}
我觉得这可行吗? 可能想要调整for循环的计数器。
此代码可能对您有所帮助:
$arr = $_SESSION["followers"]['data'];
$id = 42114932;
$count = count($arr);
$foundArr = array();
for ($i = 0; $i< $count; $i++) {
if ($arr['id'] == $id) {
$foundArr[$i] = $arr[$i];
break;
}
}
print_r($foundArr)
以下守则是不言自明的:
<?php
$_SESSION["followers"];
echo "<pre>";
print_r($_SESSION["followers"]);
echo "</pre>";
$yourID = 42114932;
for($x=0;$x<(count($_SESSION["followers"]['data']));$x++){
if($yourID == $_SESSION["followers"]['data'][$x]['id']){ //compare your id to each record
echo "Full name : ".$array['data'][$x]['full_name'];
echo "<br>Username : ".$array['data'][$x]['username'];
echo "<br>Profile picture : ".$array['data'][$x]['profile_picture'];
echo "<br>";
}
}
function getMetaInfo(array $array, $id, $arrayBranch = NULL){
if($arrayBranch === NULL){
return FALSE;
}
$returnArray = array();
foreach($array[$arrayBranch] as $key => $value){
if($value['id'] == $id){
unset($value['id']);
$returnArray[$id] = $value;
return $returnArray;
}
}
}
你可以尝试这样的事情:
$row = fetchData($_SESSION["followers"]['data'], 'id', 42114932); // Here you will get the comlet row of data you are searching
function fetchData($data, $column, $value){
for($i = 0, $i < count($data), i++)
{
if($data[$i][$column] == $value){
return $data[$i]; // returns a complete row.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.