سؤال

I have database with piwik visitor data. Piwik is showing keyword positions next to keywords in dashboard but this value is not saved in the database. Piwik is showing positions dynamically by searching google referrer url for "cd=" value which is keywords position for given keyword.

I would like to do the same in my panel.

I am getting all referring urls from google and than exploding them by & sign.

Problem I have is that some of the url strings contain cd= as a 4th key and some as 5th key.

How to find and print all cd= values from arrays like that?:

Array
(
    [0] => http://www.google.com/url?sa=t
    [1] => rct=j
    [2] => q=keyword%20one
    [3] => source=web
    [4] => cd=1
    [5] => ved=0CC0QFjAA
    [6] => url=http%3A%2F%2Fwww.domain.com%2F
    [7] => ei=RqmrUbP0Muf1igKr_4GYAQ
    [8] =>
)



Array
(
    [0] => http://www.google.com.au/url?sa=t
    [1] => rct=j
    [2] => q=
    [3] => esrc=s
    [4] => source=web
    [5] => cd=3
    [6] => ved=0CDUQFjAC
    [7] => url=http%3A%2F%2Fwww.domain.com%2F
    [8] => ei=2nKsUbTYB8m3rgfNtoC4DA
    [9] => usg=AFQjCNEQgdDpqHBsfjeEBKoyKONAG-pepg
    [10] => bvm=bv.47244034,d.bmk
    [11] => cad=rja
)

Thanks

هل كانت مفيدة؟

المحلول

Instead of spliting by & I would suggest using parse_url and parse_str

$parts = parse_url($url);
$query = array();
parse_str($parts["query"], $query);

Then you can access the 'cd' values using

$query["cd"];

نصائح أخرى

The annoyingly named parse_str parses query strings and could be used instead:

$args = parse_str($queryStr);
$cd = $args['cd'];

You should use the php function array_search. From official documentation:

array_search — Searches the array for a given value and returns the corresponding key if successful

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

Since your value is stored in key 4 or key 5 $explode_array = explode('=', arr[4]); OR $explode_array = explode('=', arr[5]);

if(($explode_array[0] == 'cd') && is_numeric($explode_array[1])) echo "CD value = ".$explode_array[1];

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top