I'm having trouble finding the right function to rearrange my multidimensional-array. I will explain using an example.
so i have three different arrays, let's say:
$ID (containing n numbers)
$Name (containing n names)
$Explanation (containing n explanations)
I have tried array($id, $name, $explanation), which returns a new array, containing the above three arrays as they were before. However I would like to have my new array in the following way:
array(
array (1[0], football[0], played on grass[0])
array (2[1], swimming[1], played in the water[1])
array (3[2], diving[2], played under water[2])
....
array (n+1[n], basketball[n], played indoors[n])
)
I would like my array this way so it can be processed more easily into my database. Thanks in advance!
I assume that all the three arrays are equal in length say $arr1,$arr2,$arr3, Try:
$result = array();
foreach($arr1 as $key=>$val){
$result[] = array($val,$arr2[$key],$arr3[$key]);
}
Then for re-indexing result array starting from index 1 you can try like,
$result = array_unshift($result,null);
unset($result[0]);
Related
Here is my code:
<?php
//header code to define as json and if $_GET statement...
$JSONArrayA[$variableA] = array('id' => $idA, 'test' => $testVariableA);
$JSONArrayB[$variableB] = array('id' => $idB, 'test' => $testVariableB);
//current code resulting in ["ArrayArray"]
$FinalJSONArray[] = $JSONArrayA . $JSONArrayB;
echo json_encode($FinalJSONArray);
?>
My question: How do I make the array contain two or more arrays? Any help appreciated.
array_merge
$FinalJSONArray = array_merge($JSONArrayA, $JSONArrayB);
Merges the elements of one or more arrays together so that the values
of one are appended to the end of the previous one. It returns the
resulting array.
If you want to instead return an array containing the other two arrays themselves,
use
$FinalJSONArray = array($JSONArrayA, $JSONArrayB);
Try
$FinalJSONArray[] = $JSONArrayA;
$FinalJSONArray[] = $JSONArrayB;
This will reult in 2 sub arrays. If you want them merged use:
$FinalJSONArray[] = $JSONArrayA+$JSONArrayB;
"+" with two arrays unions them (see: http://php.net/manual/en/language.operators.array.php)
Depending on what you want your JSON to look like
$FinalJSONArray = array($JSONArrayA,$JSONArrayB);
I have an array which contain multiple values inside it, all i want is to find duplicate items and add the number of times they are inside an array. Here goes an example
$someVar = array('John','Nina','Andy','John','Aaron','John','Zack','Kate','Nina');
I want my final result to look like
John = 3;
Nina = 2;
and so on.
EDIT | These values are dynamic i have no idea what these names going to be.
Thanks
Use array_count_values() and array_filter() to achieve this.
$result = array_filter( array_count_values( $someVar), function( $el) {
return $el > 1;
});
$result will be an associative array containing the names as keys and the number of times they occur as values, but only if they were duplicated in the $someVar array.
Here is a demo showing the correct output.
I'm trying to return a list of course id's from my database with PDO. I can access the data, however, I only want to return an array of unique id's i.e.
This
1,2,2,3,4,4
Becomes
1,2,3,4
I'm using the code below
$sth = $dbh->prepare('SELECT courseId from training');
$sth->execute();
$row = $sth->fetchAll();
$result = array_unique($row);
print_r($result);
But, it returns only 1 id:
Array ( [0] => Array ( [courseId] => 8 [0] => 8 ) )
If I print_r $row I can see all my courseId's
What am I doing wrong?
What am I doing wrong?
You are not reading the friendly manual on array_unique, where you can see this:
Note: Two elements are considered equal if and only if (string) $elem1
=== (string) $elem2. In words: when the string representation is the same. The first element will be used.
Since $result contains arrays, and the string representation of each of them is the same ("Array" IIRC) then all the elements compare "equal" and only the first is left.
How to solve the problem: Several ways.
One would be to let the database do it for you with SELECT DISTINCT.
Another would be to go from an array of arrays to an array of just ids, and then array_unique will work just fine. This can be simply done with a foreach loop, or (probably better) with array_map, e.g:
$ids = array_map(function($el) { return $el['courseId']; }, $row);
$unique = array_unique($ids);
Perhaps you would be better off by doing this query:
SELECT DISTINCT courseId FROM training
That way the data coming from the database is already unique and there is no need to use array_unique.
Its the comaprison array_unique is using. I would just do this in the query by using DISTINCT.
i have two arrays i.e$ar1=array("Mobile","shop","software","hardware");and$arr2=arry("shop","Mobile","shop","software","shop")
i want to compare the elements of arr2 to arr1 i.e
foreach($arr2 as $val)
{
if(in_array($val, $arr1))
{
//mycode to insert data into mysql table
variable++; // here there should be a variable that must be increamented when ever match found in $arr2 so that it can be saved into another table.
}
$query="update table set shop='$variable',Mobile='$variable'.......";
}
the $variable should be an integer value so that for later use i can use this variable(shop i.e in this example its value should be 3) to find the match.
My question is how can i get the variable that will increamented each time match found.
Sorry, I don't fully understand the purpose of your code. You can use array_intersect to get common values and array_diff to get the unique values when comparing two arrays.
i want to compare the elements of arr2 to arr1 i.e
Then you are essentially doing the same search for shop three times. It's inefficient. Why not sort and eliminate duplicates first?
Other issues. You are comparing arr2 values with the ones in arr1, which means the number of repetation for "shop" will not be 3 it will be one. Doing the opposite might give you the number of repetation of arr1[1] in arr2 =3.
There are multitude of ways to solve this problem. If efficiency is required,you might wish to sort so you don't have to go beyond a certain point (say s). You can learn to use indexes. Infact the whole datastructure is revolved around these kinds of things - from quick and dirty to efficient.
Not sure I understand the connection between your two arrays. But you can use this to count how many items are in your second array:
$items = array("shop","Mobile","shop","software","shop");
$count = array();
foreach($items as $item)
{
if(isset($count[$item]))
{
$count[$item]++;
}
else
{
$count[$item] = 1;
}
}
print_r($count); // Array ( [shop] => 3 [Mobile] => 1 [software] => 1 )
I am taking over a large project, and a lot of nested arrays are defined for option select lists to be used with form_dropdown() and form_multiselect() in Codeigniter. However, these arrays simply have values set and not corresponding keys.
Here's an example:
$lists['roomItems'] = array('Private telephone','Television cable/satellite','Personal furniture/decorations','Computer','Radio');
$lists['busRoute'] = array('Yes','No');
$lists['transport'] = array('Medical appointments','Dental appointments','Dialysis center','Wound care center','Religious services',
'Shopping services');
What I'd like to do is recursively go through $lists and make the keys equivalent to the values. For a single array, I tried foreach($lists['roomItems'] as $key=>value) and tried setting the key equal to the value, but it didn't take.
Can anyone help? I have about 30 items in the $lists array plus other ones that I'd re-use this code, so simply manually changing the pointers isn't really something I'd like to do. Thanks!
mhmmm what about:
$newList = array();
foreach($lists as $k=>$v) $newList[$k] = array_combine($v,$v);
should do the trick