I am using the PDO Api, and using the fetchAll() returns a Multiple Dimensional Array; This snippet below is just a test scenario; I just want to know if it's possible.
$LeUsername = "BravoSlayer";
$sth = $dbh->prepare("SELECT * FROM users WHERE Username='$LeUsername'");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
$ArraySearch = search_array($result, $LeUsername);
Output is as below:
Array ( [0] => Array ( [ID] => 1 [0] => 1 [Username] => bravoslayer [1] => bravoslayer [Password] => thisisatest [2] => thisisatest ) )
I want to search through the multi-dimensional array to return the key. IN this case it will be 0 so I can just associate another variable variable for $Array1 = $Array1['0'] so from then I can do:
$Username = $Array1['Username'];
Judging by your question. You could search the primary array within a foreach loop and use in_array to return the correct array.
Use this as your reference.
function Search_Array($Array, $SearchDilema)
{
foreach ($Array AS $CheckKeys)
{
if (in_array($SearchDilema, $CheckKeys))
{
return $CheckKeys;
}
else
{
$ErrorMsg = "No Results Found! Check Your Search Dilema";
return $ErrorMsg;
}
}
}
Related
I am new in learning php and array . I have to create an associative array from another array . In addition The array must be returned in alphabetical order based upon the key names.
this is the input array
$customerTransactions = [
'bill=9898',
'bob=772',
'james=2672',
'jim=9872',
'luke=2665',
'jim=10000'
];
The output array should be like
$outputarray = [
'bill' => 9898,
'bob' => 772,
'james' => 2672,
'jim' => 19872,
'luke' => 2665
],
I am trying to create a function which will return the output array .
public function getCustomerBalances($customerTransactions)
{
$max = sizeof($customerTransactions);
$str = implode(",", $customerTransactions);
$outputarray = print_r (explode("=",$str));
return array($outputarray);
}
But result of this array is this this
Array(
[0] => bill
[1] => 9898,bob
[2] => 772,james
[3] => 2672,jim
[4] => 9872,luke
[5] => 2665,jim
[6] => 10000)
What can I do to correct it
You want to use explode not implode.
Below I have looped through your array of strings and explode each of the values in the array by the equals operator to get a new array that holds both the customer name and the transaction ID.
I am then populating a new array called $data with the results from this explosion, the first element in the $result array is the customer name, and the second element is the transaction ID.
Once you've got the array outputing correctly, you mentioned you wanted to order them alphabetically, to do this you would use ksort().
This is simple enough, you'd just need to call this function on the output array like so:
ksort($data);
This should work for you:
public function getCustomerBalances($transactions) {
$data = [];
foreach($transactions as $v) {
$result = explode('=', $v);
$data[$result[0]] = $result[1];
}
ksort($data);
return $data;
}
This question already has answers here:
How can I remove duplicates in an object array in PHP?
(2 answers)
Closed 8 years ago.
When I print $online_performers variable I want to get a unique value for id 2. Do I need to convert them in standard array first or is that possible without it? (remove all duplicates).Please check my new code for this.
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[2] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[3] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
to
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
PHP has a function called array_filter() for that purpose:
$filtered = array_filter($array, function($item) {
static $counts = array();
if(isset($counts[$item->id])) {
return false;
}
$counts[$item->id] = true;
return true;
});
Note the usage of the static keyword. If used inside a function, it means that a variable will get initialized just once when the function is called for the first time. This gives the possibility to preserve the lookup table $counts across multiple function calls.
In comments you told, that you also search for a way to remove all items with id X if X appears more than once. You could use the following algorithm, which is using a lookup table $ids to detect elements which's id occur more than ones and removes them (all):
$array = array("put your stdClass objects here");
$ids = array();
$result = array();
foreach($array as $item) {
if(!isset($ids[$item->id])) {
$result[$item->id]= $item;
$ids[$item->id] = true;
} else {
if(isset($result[$item->id])) {
unset($result[$item->id]);
}
}
}
$result = array_values($result);
var_dump($result);
If you don't care about changing your keys you could do this with a simple loop:
$aUniq = array ();
foreach($array as $obj) {
$aUniq[$obj->id] = $obj;
}
print_r($aUniq);
Let's say we have:
$array = [
//items 1,2,3 are same
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
Then duplication depends of what do you mean. For instance, if that's about: two items with same id are treated as duplicates, then:
$field = 'id';
$result = array_values(
array_reduce($array, function($c, $x) use ($field)
{
$c[$x->$field] = $x;
return $c;
}, [])
);
However, if that's about all fields, which should match, then it's a different thing:
$array = [
//1 and 3 are same, 2 and 3 are not:
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
You'll need to identify somehow your value row. Easiest way is to do serialize()
$result = array_values(
array_reduce($array, function($c, $x)
{
$c[serialize($x)] = $x;
return $c;
}, [])
);
But that may be slow since you'll serialize entire object structure (so you'll not see performance impact on small objects, but for complex structures and large amount of them it's sounds badly)
Also, if you don't care about keys in resulting array, you may omit array_values() call, since it serves only purpose of making keys numeric consecutive.
I'm using an API which returns some JSON that I output in PHP.
PHP
$result = $api->sendRequest("getUsers", $inputParameters);
$output = json_decode($result, true);
An example of an array returned by the API. I can print out specific field values fine, but I can't figure out how to write a simple if statement that indicates whether or not there are duplicate names within the query result, specifically duplicate [fullName] fields as seen below.
Array
(
[status] => Array
(
[request] => getUsers
[recordsTotal] => 3
[recordsInResponse] => 3
)
[records] => Array
(
[0] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
[1] => Array
(
[fullName] => Jones, Bill
[firstName] => Bill
[lastName] => Jones
)
[2] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
)
)
Any help would be greatly appreciated.
Not tested, but maybe try something like
function dupeCheck($array, $attribute = 'fullName') {
$list = array();
foreach($array['records'] as $value) {
if(in_array($value[$attribute], $list))
return true;
$list[] = $value[$attribute];
}
return false;
}
Just iterating over the records, we maintain a list of values of whatever attribute, once it finds one that was already in the array, returns true.
Then just:
if(!dupeCheck($output, 'fullName')) { // no dupes in the API response }
This should work:
$data['records'] = array_map("unserialize", array_unique(array_map("serialize", $data['records'])));
Taken from here and slightly modified.
Simply create an array whose keys will be the fullnames of the entris you've seen so far:
$names = array();
foreach ($output['records'] as $entry){
If (isset($names[$entry['fullname']]){
// do some error processing
echo "'${entry['fullname']}' is a duplicate";
}
$names[$entry['fullname']] = $entry;
}
You should have all the unique entries in $names.
PHP has a lot of built in array functions to help with operations like this. You could try the following:
$names = array_column($output['records'], "fullName");
if(count(array_unique($names)) < count($names)) {
... /* handle duplicate values here */
}
In addition, $names contains a unique array of all the fullName columns from the original array for easy access and traversing. You can use this inside the above if statement to determine which names are duplicates like so:
$names_count = array_count_values($names);
foreach($names_count as $key => $value) {
if(value > 1) {
$dupes[] = $key;
}
}
References:
PHP Array Functions
array_column()
array_unique()
array_count_values()
This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
in_array() and multidimensional array
Got the following array returned from a database using this code:
$skus = array();
$result = mysql_query($sql);
if($result){
while($rows = mysql_fetch_array($result)){
$skus[]=$rows;
}
}
Results:
Array (
[0] => Array {
[0] => PUBELI
[group_sku] => PUBELI
)
[1] => Array (
[0] => PUBESSENTIALS
[group_sku] => PUBESSENTIALS
)
[2] => Array (
[0] => PUBMGRPROGROUPED
[group_sku] => PUBMGRPROGROUPED
)
[3] => Array (
[0] => PUB25GROUPED
[group_sku] => PUB25GROUPED
)
)
I'm looking for this value using in_array:
if (in_array('PUBESSENTIALS', $skus))
and it returns false. Am I doing this correctly?
Why would the array values not be enclosed in quotes if the values in the DB are strings?
Don't use PHP if you may do something with MySql!
Try this solution:
$sql = "SELECT * FROM table WHERE str = 'PUBESSENTIALS'"; // some query just add WHERE
$result = mysql_query($sql);
if($result) $Row = mysql_fetch_array($result)
Assuming $skus is the full array shown above, then 'PUBESSENTIALS' would not be in $skus, because $sku's contains child arrays.
However, in_array('PUBESSENTIALS', $skus[1]) would return true.
try looping through each $skus element, and then checking that child element for in_array(value, childArray)
You are only looking into the first array, and not any other array. You should look through each to test every sub-array. Something like this could do the job:
foreach($skus as $sku) {
if (in_array('PUBESSENTIALS', $sku)) {
return true;
}
}