how to remove duplicate array value from multidimensional associative array? - php

contains the following i am trying get array_unique value from multidimensional associative array
Here, i am only showing only sample array which is similar to this.
$array = ['games'=>[['vollyball', 'football'], ['vollyball', 'football'], ['rubby', 'chess']]];
Here is tried so for
foreach ($array as $key => &$value) {
$value = array_unique($value);
}
echo "<pre>";
print_r($array);
echo "</pre>";
exit;
Here i am expecting output is,
$array = ['games'=>[['vollyball', 'football'], ['rubby', 'chess']]];
Here the array should be same even after removing duplicate from multidimensional array.
Thanks for your time and suggestions.

you could try the following:
$a=array_values(array_unique(array_merge(...$array['games'])));
This assumes that all your usable values are below $array['games'].
Edit:
Here is another way, using array_walk:
array_walk($array['games'],function($itm){global $res; $res[json_encode($itm)]=$itm;});
echo json_encode(array_values($res));
I don't like the global $res array very much, but this is a way forward, I believe. In the callback function of array_walk() I add all values to an associative array ($res). The keys are JSON representations of their actual values. This way I will overwrite identical values in the associative array $res and will end up with a set of unique values when I apply the array_values() function at the end to turn it back into a non-associative array.
The result is:
[["vollyball","football"],["rubby","chess"]]
Here is a little demo you can check out: http://rextester.com/JEKE60636
2. edit
Using a wrapper function I can now do without the global variable $res and do the operation in-place, i. e. removing duplicate elements directly from the source array:
function unique(&$ag){
array_walk($ag,function($itm,$key) use (&$ag,&$res) {
if (isset($res[json_encode($itm)])) array_splice($ag,$key,1);
else $res[json_encode($itm)]=1.;
});
}
unique($array['games']);
echo json_encode($array)
This will result in
{"games":[["vollyball","football"],["rubby","chess"]]}
see here: http://rextester.com/YZLEK39965

Related

How do I loop through multidimensional JSON array in PHP?

I want to write code to loop through a multidimensional array (4 or 5 deep) and echo all keys and values found and skip empty arrays.
$drugs = fopen("http://dgidb.org/api/v2/interactions.json?drugs=FICLATUZUMAB", "r");
$json_drugs = stream_get_contents($drugs);
fclose($drugs);
$data_drugs = json_decode($json_drugs,true);
foreach ($data_drugs as $key => $value)
...
Anyone, anyone, Ferris?
Your $data_drugs is no longer a json, after json_decode is an associative array.
You don't need any loop to see keys and values
$data_drugs = json_decode($json_drugs,true);
print_r($data_drugs);
/* or if you don't like inline */
echo'<pre>';
print_r($data_drugs);
echo'</pre>';
You can use var_dump($data_drugs) - keys and values with types, probably you don't need this
But if you want to display keys and values more ...fancy use a recursive function
function show($x){
foreach($x as $key=>$val){
echo"<p>$key : ";
if(is_array($val)){ echo". . ."; show($val);}
else{ echo"$val</p>";}}}
show($data_drugs);

Store Get-Values from form in Array PHP

I'm trying to store the users's input via the method get in an array to store it and further process it without overwriting the initial get-value. But I dont know how.. do I have to store them in a database to do that? Or can I just push every input into an array?
I believe the following should work for you... This will take all the $_GETs that you supply and put them in a new array so you can modify them without affecting the original $_GET array.
if(is_array($_GET)){
$newArr = $_GET; // modify $newArr['postFieldName'] instead of $_GET['postFieldName'] to preserve original $_GET but have new array.
}
That solution there will dupe the $_GET array. $_GET is just an internal PHP array of data, as is $_POST. You could also loop through the GETs if you do not need ALL of the GETs in your new array... You would do this by setting up an accepted array of GETs so you only pull the ones you need (this should be done anyways, as randomly accepting GETs from a form can lead to some trouble if you are also using the GETs for database/sql functions or anything permission based).
if(is_array($_GET) && count($_GET) > 0){
$array = array();
$theseOnly = array("postName", "postName2");
foreach($_GET as $key => $value){
if(!isset($array[$key]) && in_array($key, $theseOnly)){ // only add to new array if they are in our $theseOnly array.
$array[$key] = $value;
}
}
print_r($array);
} else {
echo "No $_GET found.";
}
I would just add to what #Nerdi.org said.
Specifically the second part, instead of looping through the array you can use either array_intersect_key or array_diff_key
$theseOnly = array("postName", "postName2");
$get = array_intersect_key( $_GET, array_flip($theseOnly);
//Or
$get = array_diff_key( $_GET, array_flip($theseOnly);
array_intersect_key
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
So this one returns only elements you put in $theseOnly
array_diff_key
Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
So this one returns the opposite or only elements you don't put in $theseOnly
And
array_flip
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
This just takes the array of names with no keys (it has numeric keys by default), and swaps the key and the value, so
$theseOnly = array_flip(array("postName", "postName2"));
//becomes
$theseOnly = array("postName"=>0, "postName2"=>1);
We need the keys this way so they match what's in the $_GET array. We could always write the array that way, but if your lazy like me then you can just flip it.
session_start();
if(!isset($_SESSION['TestArray'])) $_SESSION['TestArray'] = array();
if(is_array($_GET)){
$_SESSION['TestArray'][] = $_GET;
}
print_r($_SESSION['TestArray']);
Thanks everybody for helping! This worked for me!

how to Append an arrays values and keys to another array in PHP

IN PHP i have the following arrays.
And i have this array:
What i want to do is append the second array to the first one,
i tried doing it like so:
end($array1);
foreach($array2 as $key => $value ){
$array1[$key] = $value;
}
With this result:
My question is; How do i put the the values and keys of the second array into the first one?
Answer: due to the answer of Manikiran i now got the following array as a result:
array_merge() is the function you are looking for. Try the following code:
$new_array=array_merge($array1,$array2);
For more information, check out the manual

Remove element from associative array in PHP

I need to remove a element from an associative array with an string structure.
Example:
$array = array(
"one"=>array("Hello", "world"),
"two"=>"Hi"
)
I want to create a function that removes the elements like this:
function removeElement($p) {
// With the information provided in $p something like this should happen
// unset($array["one"]["hello"])
}
removeElement("one.hello");
Your base array is associative, the inner array (key one) is not, its a indexed array, which you can not access via ["hello"] but rather [0].
You can remove the hello value by using the unset function, but the indexes will stay as they are:
$array = ['Hello', 'World']; // array(0: Hello, 1: World)
unset($array[0]); // Array is now array(1: World)
If you wish to keep unset and keep the array indexes in order, you can fetch the values using the array_values function after unset:
unset($array[0]);
$array = array_values($array); // array(0: World)
Or you could use array_splice.
When it comes to using a string as key for multidimensional array with a dot-separator I'd recommend taking a look at laravels Arr::forget method which does pretty much exactly what you are asking about.
This would be a static solution to your question, in any case, you need to use explode.
function removeElement($p, $array) {
$_p = explode('.', $p);
return unset($array[$_p[0]][$_p[1]]);
}
But bear in mind, this doesn't work if you have more in $p (like: foo.bar.quux)

Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.

Categories