PHP Remove duplicates from multidimensional array based on key - php

I have a multidimensional array ($array) in which the entries look like:
{ ["upload/example.gif"]=> array(5) {
["title"]=> string(12) "This is me"
["excerpt"]=> string(24) "This is a photo of a tree"
["img"]=> string(42) "upload/example.gif"
["link"]=> string(23) "http://www.google.co.uk"
["source"]=> string(6) "custom"
}
}
I need to be able to remove any duplicate values in $array based on the key. So if my array was:
$array = array( ["upload/example.gif"] => etc....
["upload/tree.gif"] => etc....
["upload/example.gif"] => etc....)
I would be able to remove one of the ["upload/example.gif"] => etc.... arrays.
I have tried:
$array = array_map('unserialize', array_unique(array_map('serialize', $array)));
but that didn't work.
Thanks in advance.

netcoder answered the question properly, I just wanted it to show up in the answer box (instead of comment).
You can't have duplicate keys in an associative array (or any array). By nature of it being an array you can be gauranteed to have unique keys.
BTW if you find duplicate data in different keys you can remove the redundant key by unsetting it.
unset($array['delete_me']);
http://php.net/manual/en/function.unset.php

Related

Create array from MySQL results, and add new items

I've got a MySQL search query outputting to an array:
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
What I'd like to be able to is add further keys/values to each array item.
So at the moment it outputs:
array(1) {
[0]=>
array(7) {
["organisation"]=>
string(32) "7a5fddaceecec75c9a13cb329f6b4b15"
["date_created"]=>
string(10) "2017-08-04"
}
}
I'd like it also to include this on the end of the array:
'name' => getName($result['name'];
I assume I do that with array_push and a while loop? I just can't figure out how.
Thanks
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:
$data[$key] = $value;
It is not necessary to use array_push.

php sort array without custom function

Here is an extract of my test code and data:-
//Update Array
$civs[1][1]="1";
$civs[1][2]="Inca";
$civs[2][1]="2";
$civs[2][2]="India";
//Sort Array
array_multisort($civs[0][2], SORT_DESC, SORT_STRING,
$civs[0][1], SORT_NUMERIC, SORT_DESC);
Output:-
Warning: array_multisort(): Argument #1 is expected to be an array or
a sort flag in ~/test.php on line 3
array(3) { [1]=> array(2) { [1]=> string(1) "1" [2]=> string(4) "Inca" } [2]=> array(2) { [1]=> string(1) "2" [2]=> string(5) "India" } [0]=> array(2) { [2]=> NULL [1]=> NULL } }
Problem statement
Depending on what the User selects I need to sort the array in PHP either on the 1st (numeric) or 2nd (alphanumeric) element of the 2nd part of the array but can't see how to do that, the various PHP sorts don't seem to allow you to tell it what is to be sorted on, have tried the above code . The PHP Manual for uksort says "If the array you wish to sort needs to be sorted by some non-trivial criteria," well numeric is about as trivial as it gets!
I've been looking at this for a couple of hours now and am sure I must be missing something as all I can see is that I have to write a custom function but surely PHP knows how to do simple sorts based on numeric or text values?
Main question I found was this:- How can I sort arrays and data in PHP? and I also spent a fair bit of time browsing through http://php.net/manual/en/array.sorting.php.
Apologies if I have missed something obvious.

PHP shuffle not working like expected on my nested array

I have a nested array of arrays, and I want to shuffle the inner arrays. My code looks like this (simplified):
$a = array(array('banana', 'peach'), array('ding', 'dong'), array('oh snow'));
foreach ($a as &$arr) {
shuffle($arr);
}
var_dump($a);
The var_dump outputs this:
array(3) { [0]=> array(2) { [0]=> string(5) "peach" [1]=> string(6) "banana" } [1]=> array(2) { [0]=> string(4) "ding" [1]=> string(4) "dong" } [2]=> &array(1) { [0]=> string(7) "oh snow" } }
As you can see in the output, the first two subarrays work, but the third subarray is linked by reference in the output...
In my full app, this last array-link causes problems, but rather than working around the issue, I want to fix this shuffle thing...
Cheers!
This has to do with how PHP stores references to array elements. It cannot reference an element of an array, only values. Therefore it has to store the value array('oh snow') in a "slot" of the symbol table, then make $arr and $a[2] a reference to that value.
To fix this, unset($arr) after the loop. That way only a single variable is referencing the value, which will then be made a regular array index again. Unsetting references after a foreach is good practice anyway, since there are many such gotchas.

Transform array

I'd like to transform input array from:
array(1) {
["option"]=>
array(2) {
[0]=>
string(8) "fdfsafsd"
[1]=>
string(7) "dasdasd"
...
}
}
to
array(array('option' => "fdfsafsd"), array('option' => "dasdasd"),...)
The key "option" can be whatever...
What would be the best practice?
Thanks!
Best practice would be to leave your array as it is. If you want to "transform" it, you need to assign new keys for values found in the "options" key.
$new_array = $old_array['options'];
That would get what you specified in your question, however I don't see why you'd do that in the first place.
you want to have an associative array with all the value on one key ???
That seems impossible because an associative array is one key => one Value.
so you probably want an array list, you can obtain it easely by:
$myArray = $originalArray['option']
which will be like that:
array("fdfsafsd", "dasdasd",...)

Get value from a array

update
how can I retrieve this value? I need to do that if I will write the value to my database.
array(3) {
[1]=> NULL
[2]=> array(2) {
[123]=>
int(123)
[122]=>
int(0)
}
[3]=> NULL
}
There is something missing in your output. I assume it looks something like:
// var_dump($array);
array(1) {
[0]=>
string(2) "39"
}
so you can access the value with $array[0]. Simple array access.
As arrays are the most important data structure in PHP, you should learn how to deal with them.
Read PHP: Arrays.
Update:
Regarding your update, which value do you want? You have a multidimensional array. This is what you will get:
$array[1] // gives null
$array[2] // gives an array
$array[2][123] // gives the integer 123
$array[2][122] // gives the integer 0
$array[3] // gives null
Maybe you also want (have) to loop over the inner array to get all values:
foreach($array[2] as $key => $value) {
// do something with $key and $value
}
As I said, read the documentation, it contains everything you need to know. Accessing arrays in PHP is not much different than in other programming languages.
The PHP manual contains a lot of examples, it is a pretty could documentation. Use it!
If your array is referenced as $myArray, you can get the string 39 via $myArray[0], i.e., this zeroth item.

Categories