[英]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.