How retrieve specific duplicate array values with PHP

大城市里の小女人 提交于 2019-12-13 11:13:27

问题


$array = array(
array(
    'id' => 1,
    'name' => 'John Doe',
    'upline' => 0
),
array(
    'id' => 2,
    'name' => 'Jerry Maxwell',
    'upline' => 1
),
array(
    'id' => 3,
    'name' => 'Roseann Solano',
    'upline' => 1
),
array(
    'id' => 4,
    'name' => 'Joshua Doe',
    'upline' => 1
),
array(
    'id' => 5,
    'name' => 'Ford Maxwell',
    'upline' => 1
),
array(
    'id' => 6,
    'name' => 'Ryan Solano',
    'upline' => 1
),
array(
    'id' =>7,
    'name' => 'John Mayer',
    'upline' => 3
),

); I want to make a function like:

function get_downline($userid,$users_array){
}

Then i want to return an array of all the user's upline key with the value as $userid. I hope anyone can help. Please please...


回答1:


If you need do search thru yours array by $id:

foreach($array as $value)
{
   $user_id = $value["id"];
   $userName = $value["name"];
   $some_key++;

   $users_array[$user_id] = array("name" => $userName, "upline" => '1');
}

function get_downline($user_id, $users_array){
     foreach($users_array as $key => $value)
     {
         if($key == $user_id)
         {
              echo $value["name"];
              ...do something else.....
         }
     }
}

or to search by 'upline':

function get_downline($search_upline, $users_array){
         foreach($users_array as $key => $value)
         {
             $user_upline = $value["upline"];
             if($user_upline == $search_upline)
             {
                  echo $value["name"];
                  ...do something else.....
             }
         }
    }



回答2:


You could do it with a simple loop, but let's use this opportunity to demonstrate PHP 5.3 anonymous functions:

function get_downline($id, array $array) {
    return array_filter($array, function ($i) use ($id) { return $i['upline'] == $id; });
}

BTW, I have no idea if this is what you want, since your question isn't very clear.




回答3:


Code :

function get_downline($userid,$users_array) 
{
    $result = array();

    foreach ($users_array as $user)
    {
        if ($user['id']==$userid)
            $result[] = $user['upline'];
    }
    return result;
}
?>

Example Usage :

get_downline(4,$array);


来源:https://stackoverflow.com/questions/10067731/how-retrieve-specific-duplicate-array-values-with-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!