-1

I have this 2d array that represent outgoing links of each page returned by search engine, now I have to find number of inbound links of each page.

eg 1 is present in sub array in key2,3,4,5,6 so its number of inbound will be 5.

I need this in PHP.

$links = array( 
        1 => array(2,3,4,5,6),
        2 => array(1,3,4,5,6),
        3 => array(1,2,4,5,6),
        4 => array(1,2,3,5,6),
        5 => array(1,2,3,4,6),
        6 => array(1,2,3,4,5),
        7=> array (11),
        8=>array(7,9),
        9=> array(7),
        10=> array(8),
        11=> array(8,10),

);
halfer
  • 19,824
  • 17
  • 99
  • 186
parul
  • 1
  • 1
  • It might be easier to help if you could show us what you want the output to be. Could you please edit your question to include an example of the result you want? – Eric Renouf May 12 '15 at 03:47
  • 1
    http://stackoverflow.com/a/12232970/689579 ? – Sean May 12 '15 at 03:47
  • @EricRenouf for eg for above array number of inbound links for 1 will be 5 ,as 1 is present in subarray at location 2,3,4,5,6 – parul May 12 '15 at 03:50
  • possible duplicate of [Count total of subarrays with certain values in PHP](http://stackoverflow.com/questions/12232960/count-total-of-subarrays-with-certain-values-in-php) – Eric Renouf May 12 '15 at 03:52
  • Then I think Sean is right, his link likely is your answer – Eric Renouf May 12 '15 at 03:52
  • i have to dynamically calculate the number of keys in which 1st key is present similarly the number of keys in which 2nd key is present and so on – parul May 12 '15 at 03:54
  • so you want all results, not just the `1` value? – Sean May 12 '15 at 03:54
  • yess i want duplicate count for all the keys – parul May 12 '15 at 03:55

1 Answers1

1

probably a cleaner way, but one way is to create a new array, loop over your existing array, and add to the new array using the value as the key.

$results=array();
foreach($links as $link){
    foreach($link as $value){
        $results[$value] = isset($results[$value]) ? $results[$value]+1 : 1;
    }
}

with your example data, your results would look like -

Array ( 
    [1] => 5 
    [2] => 5 
    [3] => 5 
    [4] => 5 
    [5] => 5 
    [6] => 5 
    [7] => 2 
    [8] => 2 
    [9] => 1 
    [10] => 1 
    [11] => 1
)
Sean
  • 12,443
  • 3
  • 29
  • 47
  • bt it is not counting for key 1 – parul May 12 '15 at 04:04
  • what do you mean? You said `1 is present in sub array in key2,3,4,5,6 so its number of inbound will be 5` and in my example `[1] => 5`. How is `it is not counting for key 1`? – Sean May 12 '15 at 04:09
  • `2` is in `1,3,4,5,6` so `[2] => 5`, .... , `7` is in `8,9` so `[7] => 2`, .... , and `11` is in `7` so `[11] => 1` – Sean May 12 '15 at 04:11