Getting an element from array in PHP - php

With the following array, how would I just print the last name?
Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.
$array = Array
(
[0] => Array
(
[name] => FirstName
[value] => John
)
[1] => Array
(
[name] => LastName
[value] => Geoffrey
)
[2] => Array
(
[name] => MiddleName
[value] => Smith
)
)

I would normalize the array first:
$normalized = array();
foreach($array as $value) {
$normalized[$value['name']] = $value['value'];
}
Then you can just to:
echo $normalized['LastName'];

If you are not sure where the lastname lives, you could write a function to do this like this ...
function getValue($mykey, $myarray) {
foreach($myarray as $a) {
if($a['name'] == $mykey) {
return $a['value'];
}
}
}
Then you could use
print getValue('LastName', $array);

This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:
`foreach($array as $arr){
(if $arr['name'] == "lastName")
print_r($arr['value']
}`

Related

selecting value of particular index with PHP foreach

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

PHP - Detecting duplicate values in a nested array

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()

How to not echo array if previous one's key has been echoed already

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;
}));

Access corresponding value in PHP array given a certain known value

supposing I have an array like the one below:
Array
(
[0] => Array
(
[id] => 1
[title] => Group1
[description] => This is the group1.
)
[1] => Array
(
[id] => 2
[title] => Group2
[description] => This is group2.
)
)
Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?
Thanks for any help.
Try this :
$title = "Group2";
foreach($your_array as $val){
if($val['title'] == $title){
echo $val['description'];
break; //cut back on unnecessary looping
}
}
Try like this
foreach($myarray as $val){
if($val['title'] == "Group2"){
echo 'This is description '.$val['description'];
}
}
You'll have to iterate over the main array and scan it for that title.
Assuming your main array is called $groups :
$title = 'Group2';
foreach($groups as $key => $group){
if ($group['title'] == $title){
$groupDescription = $group['description'];
// if you need to reference this group again, save it's key.
$groupKey = $key;
}
}
You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories