I'm using the Google API to extract data from Analytics. But I can't remove the duplicates in my array. I have checked the forum and array_unique functionalities seems to do the trick but I can't make it working. Any ideas?
Much appreciated!
<?php
$jsonurl = "URL";
$json = file_get_contents($jsonurl,0,null,null);
$arrayJson = json_decode($json, true);
$arrayTable = $arrayJson['rows'];
?>
<table style="border 1px solid" width="700px">
<tr>
<td>ID</td>
<td>Source</td>
<td>Medium</td>
<td>Column 4</td>
<td>Column 5</td>
<td>Column 6</td>
<td>Column 7</td>
<td>Column 8</td>
</tr>
<?php for($i = 0; $i < count($arrayTable); $i++) { ?>
<tr>
<?php for($ii = 0; $ii < count($arrayTable[$i]); $ii++) { ?>
<td> <?php print_r($arrayTable[$i][$ii]); ?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
You can use array_unique like below:
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)
You must do it before the cycle. For example:
$arrayTable = array_unique($arrayJson['rows']);
The problem is because you are trying to use array_unique
on a multi-dimensional array. It is designed to only work on the first level of an array. For example:
$a = array('crazy', 'sane', 'mad', 'sane');
print_r( array_unique($a) );
The above will give:
array( 'crazy', 'sane', 'mad' );
However, if you try:
$a = array(
0 => array('crazy'),
1 => array('sane'),
2 => array('mad'),
3 => array('sane'),
);
print_r( array_unique($a) );
You will get:
Array ( [0] => Array ( [0] => crazy ) )
This is because array_unique
converts all values to strings before it does it's uniquification. In PHP all arrays produce the string Array
when cast... This is why you only get one item.
The only way you will resolve this is if you choose to have one value representing your unique value and sort / uniquify based on this. The standard approach would be to set this value as the key of the array and that will automatically create a unique list.
For example, taking the multi-dimensional array from above, we can convert to a unique array by doing the following.
$u = array();
foreach ( $a as $key => $val ) {
$u[reset($val)] = $val;
}
print_r( $u );
You will get:
Array (
[crazy] => Array (
[0] => crazy
)
[sane] => Array (
[0] => sane
)
[mad] => Array (
[0] => mad
)
)