I have the following array -
Array
(
[31] => Array
(
[0] => 3
[1] => 3
)
[33] => Array
(
[0] => 2
[1] => 1
)
)
Now for the key 31 both of the elements has same value ie 3 but not for the key 33. So I am trying to create another array which will look like.
Array
(
[31] => same
[33] => notsame
)
That means if a key from multidimensional array has got all the values same then it will have the text 'same' else 'notsame'
My code-
foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
{
foreach($v1 as $k2=>$v2)
{
if($v1[$k2] = $v1[$k2+1])
{
$newArr[$k1] = 'same';
}
else
{
$newArr[$k1] = 'notsame';
}
}
}
echo '<pre>';
print_r($newArr);
echo '</pre>';
And the output is showing 'notsame' for both keys.
Array
(
[31] => notsame
[33] => notsame
)
Any help is highly appreciated.
When you run this snippet, you will get this error
Notice: Undefined index: 2 in /in/bcqEH on line 14
See https://3v4l.org/bcqEH
This is because the code tries to compare first and second, and it tries to compare second and third element. But this third element doesn't exist. This means the comparison fails and sets the value to notsame.
To fix this, you could just compare the first two elements, e.g.
foreach ($subvaluesArr as $k1 => $v1) {
if ($v1[0] == $v1[1]) {
$newArr[$k1] = 'same';
} else {
$newArr[$k1] = 'notsame';
}
}
When you really have more than two elements, you might try array_unique
foreach ($subvaluesArr as $k1 => $v1) {
$u = array_unique($v1);
if (count($u) == 1) {
$newArr[$k1] = 'same';
} else {
$newArr[$k1] = 'notsame';
}
}
You have to break; loop after running the if-else condition.
example :
foreach($subvaluesArr as $k1=>$v1) //$subvaluesArr is the multidimensional array here
{
foreach($v1 as $k2=>$v2)
{
if($v1[$k2] === $v1[$k2+1])
{
$newArr[$k1] = 'same';
}
else
{
$newArr[$k1] = 'notsame';
}
break;
}
}
cant comment so I write it as answer. In your loop when you hit last element of an array, you ask
if($v1[$k2] == $v1[$k2+1])
where $v1[$k2+1] is "undefined" as you are out of bounds. So this last element is always false and you end up with "notsame"
Related
Hi i am working on some array operations with loop.
I want to compare array key value with the given name.
But i am unable to get exact output.
This is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => 3M
[value] => 76
)
[2] => Array
(
[label] => Test
[value] => 4
)
[3] => Array
(
[label] => Test1
[value] => 5
)
[4] => Array
(
[label] => Test2
[value] => 6
)
)
This is my varriable which i need to compare : $test_name = "Test2";
Below Code which i have tried :
$details // getting array in this varriable
if($details['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
But every time its returns NotFound.
Not getting what exactly issue.
#Manthan Dave try with array_column and in_array() like below:
<?php
if(in_array($test_name, array_column($details, "label"))){
return $test_name;
}
else
{
return "NotFound";
}
$details is a multidimensional array, but you are trying to access it like a simple array.
You need too loop through it:
foreach ($details as $item) {
if($item['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
I hope your array can never contain a label NotFound... :)
You have array inside array try with below,
if($details[4]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
Although foreach loop should work but if not try as,
for($i=0; $i<count($details); $i++){
if($details[$i]['label'] == $test_name)
{
return $test_name;
}
else
{
return "NotFound";
}
}
Traverse your array like this,
array_walk($array, function($v) use($test_name){echo $v['label'] == $test_name ? $test_name : "NotFound";});
Just use in_array and array_column without use of foreach loop as
if (in_array($test_name,array_column($details, 'label')))
{
return $test_name;
}
else
{
return "NotFound";
}
You need to check only the if condition like below because else meet at first time it will return the "notfound" then it will not execute.
$result = 'NotFound';
foreach ($details as $item) {
if($item['label'] == $test_name)
{
$result = $test_name;
}
}
return $result;
or
$result = 'NotFound';
if (in_array($test_name,array_column($details, 'label')))
{
$result = $test_name;
}
return $result;
If the $gymnast object is not in the $gymnasts array, I add it to my table. However, when I add the same object to the array, in_array() fails (returns 1) and the duplicate object is added to the array. Using print_r, I saw that the $gymnast object is clearly the same as the first element in the $gymnasts array, so why is this happening? How do I fix this?
$gymnasts array
Array ( [0] => Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg ) [1] => Gymnast Object ( [name] => Shawn Johnson [age] => 25 [height] => 4' 11" [olympicYear] => 2008 [medalCount] => 4 [image] => shawn.jpg ))
$gymnast object
Gymnast Object ( [name] => Nastia Liukin [age] => 27 [height] => 5' 3" [olympicYear] => 2008 [medalCount] => 5 [image] => nastia.jpg )
index.php
<?php
function isDuplicateEntry($gymnast, $gymnasts) {
foreach ($gymnasts as $gym) {
$gymArr = get_object_vars($gym);
$gymnastArr = get_object_vars($gymnast);
if (count(array_diff($gymnastArr, $gymArr)) == 0) { //gymnast object already exists in array
return true;
}
else {
return false;
}
}
}
//Add gymnast when press add submit button
if(isset($_POST['add'])){
//Set gymnast array to all gymnasts in data.txt
$gymnasts = read_file($filename);
//If form has valid elements & no duplicats, add to data.txt file
if($valid_name && $valid_age && $valid_feet && $valid_inches && $valid_olympicYear && $valid_medalCount && $valid_image){
$gymnast = get_gymnast_from_form();
//Make sure gymnast is not null
if(!is_null($gymnast)){
//Prevent from adding duplicates
if(!isDuplicateEntry($gymnast, $gymnasts)){
//Write task to file
write_file($filename, $gymnast);
//Add gymnast to global var gymnasts array
$gymnasts[] = $gymnast;
echo'<div class ="title">Gymnast Added!</div>';
}
}
}
?>
You cannot use in_array for multidimensional objects straight away. You will have to loop them to find out the match.
Use array_intersect to check if the array is present in another array.
$flag = 0;
foreach ($gymnasts as $gym {
if (count(array_intersect($gymnast, $gym)) == count($gym)) {
echo 'It is present.';
$flag = 1;
break;
}
}
if ($flag == 0) {
echo 'Not present in array';
}
You can also use array_diff to match arrays.
$flag = 0;
foreach ($gymnasts as $gym) {
if (count(array_diff($gymnast, $gym)) == 0) {
echo 'It is present.';
$flag = 1;
break;
}
}
if ($flag == 0) {
echo 'Not present';
}
array_intersect
array_diff
ideone link array_intersect
ideone link array_diff
You can use array_filter with count:
$is_in_array = count(array_filter($gymnasts, function($member) use ($gymnast) {
return $member == $gymnast;
})) > 0;
I have this array:
Array
(
[one] => Array
(
[a] => 0
[b] => 1
[c] => 1
[d] => 3
[e] => 1
)
[two] => Array
(
[a] => 0
[b] => 3
[c] => 1
[d] => 4
[e] => 1
)
[three] => Array
(
[a] => 3
[b] => 1
[c] => 2
[d] => 4
[e] => 1
)
)
And I want to convert it into single array with the values are the sums of every value inside the inner array, so it could be like this:
Array
(
[a] => 3
[b] => 5
[c] => 4
[d] => 11
[e] => 3
)
How to achieve it?
EDIT
This was the best what I've done:
$rest = array();
foreach($result as $key => $value){
if(is_array($value)) {
foreach($value as $k => $val){
$rest[$k] = array_sum($value);
}
}
}
But it returns all values to be the same, i.e all 9 on every inner key.
You can get the keys from the first child array with array_keys, and then use array_sum and array_column to generate the array of sums.
foreach (array_keys($your_array['one']) as $key) {
$sums[$key] = array_sum(array_column($your_array, $key));
}
array_column does require php >= 5.5.
Incidentally, what you already had was really close to working. If you change
$rest[$k] = array_sum($value);
to
$rest[$k] += $val;
It should be good to go. What you had before was repeatedly summing the entire sub-array and assigning it to each letter key, but you just needed to add the current value to that letter key.
$rest[$k] += $val; will work, but give you undefined index notices for the first sub-array. You can fix that by checking isset before assigning, like this:
$rest[$k] = isset($rest[$k]) ? $rest[$k] + $val : $val;
I would say modifying your original code to work this way would probably be better than redefining array_column if you can't use it.
You have multidimensional Array , that why have to use two loop for understanding in beginning level. First loop will get Every Object of Array , Second Array will get the Params of Object.
$finalArray = array();
for($i = 0;$i<count($array);$i++){ // GET ALL OBJECT FROM ARRAY
foreach($array[$i] as $key=>$value){ // GET ALL KEY FROM OBJECT
$finalArray[$key] += $array[$i][$key];
}
}
print_r($finalArray);
Work on all version of PHP
You can use array_sum and loop over the first dimension
foreach ($array as $key => $values) {
$newArray[$key] = array_sum($values);
}
Credit to Don't Panic's answer above and this answer which is providing array_column() alternative for PHP version < 5.5
// if array_column function don't exist, add array_column function
if (! function_exists('array_column')) {
function array_column(array $input, $columnKey, $indexKey = null) {
$array = array();
foreach ($input as $value) {
if ( ! isset($value[$columnKey])) {
trigger_error("Key \"$columnKey\" does not exist in array");
return false;
}
if (is_null($indexKey)) {
$array[] = $value[$columnKey];
}
else {
if ( ! isset($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not exist in array");
return false;
}
if ( ! is_scalar($value[$indexKey])) {
trigger_error("Key \"$indexKey\" does not contain scalar value");
return false;
}
$array[$value[$indexKey]] = $value[$columnKey];
}
}
return $array;
}
}
// sum up the values
$rest = array();
foreach($result as $key => $arr){
if(is_array($arr)) {
foreach($arr as $k => $val){
$rest[$k] = array_sum(array_column($result, $k));
}
}
}
Not sure why I can't this to work. My json is:
[values] => Array
(
[0] => Array
(
[field] => id1
[value] => 985
)
[1] => Array
(
[field] => id2
[value] => 6395
)
[2] => Array
(
[field] => memo
[value] => abcde
)
I simply want the values of id2
I tried:
foreach ($json['values'] as $values) {
foreach ($json as $key=>$data) {
if ($data['field'] == 'id2') {
$result = $data['value'];
print '<br>value: '.$result;
}
}
}
Thanks. I know this should be relatively simple and I'm sure I've done this correctly before.
there's no need for inner loop, after the first one $values already contain the exact array that you are looking for
foreach ($json['values'] as $values) // $values contain
{
if ($values['field'] == 'id2')
{
$result = $values['value'];
print '<br>value: '.$result;
}
}
foreach ($json['values'] as $values) { //you're looping your first array, puttin each row in a variable $values
foreach ($values as $key=>$data) { //you're looping inside values taking the array index $key and the value inside that index $data
if ($key == 'id2') { //test if $key (index) is = to id2
print '<br>value: '.$value; // print the value inside that index
}
}
}
this is just an explanation, to what is going wrong with your code, but as #Pawel_W there is no need for the second foreach loop you can directly test
if($values['field']=='id2'){ print $values['value'];}
I think you just need to use array_search.
And here is recursive array_search ;
Assuming there might be multiple fields with the same name and you want them all as array, here's an alternative take:
array_filter(array_map(function($item) { return $item['field'] == 'id2' ? $item['value'] : null; }, $json['values']));
If your field names are always unique and you just want a single scalar:
array_reduce($json['values'], function($current, $item) { return $item['field'] == 'id2' ? $item['value'] : $current; });
(note that this one is not ideal since it will walk all the array even if match is found in first element)
And here's a gist with both in this and function form + output.
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best