PHP insert elements before, between and after some array elements - php

I've a multidimensional array of some arrays, in which the first values are ordered and included in a specific range.
Example:
A1=[[0,a],[3,b],[5,c],[6,a],[9,c]]
in which A1[i][0] are in range (0,10)
How can I obtain an array where, if the first value
(A1[i][0]) isn't a value present in the first array, e.g.
A1[i][0]==2
I insert an array with that value in the right position, with a specified second value (example A)?
Example of output i want:
A1=[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]

This will help
$A1 = [[0,'a'],[3,'b'],[5,'c'],[6,'a'],[9,'c']];
foreach($A1 as $A2) $A3[] = $A2[0];//make a new array contain keys of the first array.
for($i=0;$i<=9;$i++){
if(!in_array($i, $A3)){
$A1[] = [$i, 'A']; //check if the key not exist, make a new array with key who does not exist.
}
}
asort($A1);//sort the new element inside the array
print_r($A1);
output is,
[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]

Related

how to declare punch of array variable in Excel using PHPExcel??/

I got values of column A and B from Excel by below php code
for($i=1;$i<=$arrayCount;$i++)
{
$col_A = array(trim($allDataInSheet [$i]["A"]));
$col_B =array(trim($allDataInSheet [$i]["B"]));
}
If 'A' has 44 variable names and 'B' has 44 values.
In this scenario,How can I assign the values of 'B' to the variable names of 'A'
Please help me to solve this
Arrays in PHP can take on two different key-types and they can mix and match. Indexed by number and indexed by string. And an array can contain any value, including an array of values. This means that you can create an array that uses the names in Array A as the keys and the values in Array B as the values for those keys.
$columns = [];
// Arrays start at 0, but since these came from excel 0 is the column header.
// You want to stop 1 entry before the count of your array. Since arrays are 0 indexed, the array count is 1 larger than the last index.
for($i=1;$i<=$arrayCount-1;$i++)
{
$a = trim($allDataInSheet [$i]["A"]);
$b = trim($allDataInSheet [$i]["B"]);
// You don't need to specify the Array constructor anymore.
// You can just use brackets to create a new array.
// Not sure if you still want these, but I left them for you.
$col_A = [$a];
$col_B = [$b];
// Assign the values of B to columns in A
if(!isset($columns[$a]) {
$columns[$a] = $b;
} else {
// Debugging message - Tried to set two values to the same name.
}
}
// Do stuff with $columns
// $columns["a"] == "b"
Above, you can see that since $allDataInSheet[$i]["A"] is the string we want, we can just use that value as our key and its matching entry in B as the value for that key.
Notice how we don't let a value get added to the array if we already have that name set. If you want $columns[$a] to be an array of values, you can change it to look like this:
if(!isset($columns[$a]){
// If we don't have an entry for $columns[$a] create an array here to hold the values for possible $b's.
$columns[$a] = [];
}
// Add $b to the $columns[$a] array.
$columns[$a][] = $b;
That will treat the $columns array as an array of arrays. Meaning that each position can hold multiple values. So, we turn it into an array and just add the $b value to that position. If we come across that $a value again, we'll see that we already have that position set and we just use the array that's already there.
Notice - we do an isset check instead of an empty check because if 'b' was actually " " or false or 0 or for some strange reason, $columns[$a] doesn't change from an empty array to an array with something in it, than we don't want to erase the value that's already there.
Good Luck!

php merge elements in an array of arrays with common and different keys into a final array

Suppose I have single array of arrays. each element in the array of arrays are similar to each other as they have similar keys, but perhaps one of the keys has a unique value or one of the arrays in the array of arrays has an additional/different key. For example...
$masterArray = array(
[0]=>array(id=>'123', url=>"http://xyz.com", data=>"something", data2=>"else"),
[1]=>array(id=>'123', url=>"http://xyz.com", data=>"something", data3=>"baby"),
[2]=>array(id=>'456', url=>"http://abc.com", data=>"something", data2=>"completely"),
[3]=>array(id=>'456', url=>"http://abc.com", data=>"something", data3=>"different"),
[4]=>array(id=>'789', url=>"http://def.com", data=>"something", data2=>"is not quite"),
[5]=>array(id=>'789', url=>"http://def.com", data=>"something", data3=>"right")
);
I require a new array to be made from $masterArray that would merge the individual keys together in the array of arrays into a new key in the new array, based on matching key value pairs in each individual array.
So the final array would appear like this...
$finalArray = array(
[0]=>array(id=>'123', url=>"http://xyz.com", data=>"something", data2=>"else", data3=>"baby"),
[1]=>array(id=>'456', url=>"http://abc.com", data=>"something", data2=>"completely", data3=>"different"),
[2]=>array(id=>'789', url=>"http://def.com", data=>"something", data2=>"is not quite", data3=>"right"),
);
There's quite an array (no pun intended) of php functions that can sort / merge arrays or values, but I cannot figure out which ones to use or how to implement it!
Can anyone figure out a solution to this? It would be much appreciated.
Note: To note, I have done the following
What I have tried is the following algorithm:
create two copies of $masterArray (call them $m1 and $m2)
use two for..each loops. The first for...each loop goes through $m1, the second one through $m2
grab the current element in $m1 from the outer loop
compare the current element in $m2 from the inner loop
if the $m1[outerloopindex] matches $m2[innerloopindex] through the majority of their key values, create a new array element $x, merging their key value pairs.
push or add $x to $newArray
(and this may or may not work) remove the element compared from $m1 and $m2 (since we used them, we don't need them anymore. assume no more matches)
if the $m1[outerloopindex] does not match$m2[innerloopindex] , simply go to the next $m2[innerloopindex] value and compare again to $m1[outerloopindex] until a match is made (or not)
if no elements in $m2 match the element compared against in $m1, keep $m1[outerloopindex]
loop again going to $m1[outerloopindex+1] etc.
But unfortunately it does not seem to return the correct number of results :(
Sample code is below.
foreach($artistData as $key=>&$asset){
// 2. examine each element, its value is itself an array.
// $key returns the position
// reset the $artistData array
$artistData=array_values($artistData);
$currElement = $artistData[$key];
// 3. check for this secondary array's uid.
// loop through each element in this secondary array
$currElUid = $currElement['uid'];
$currElid = $currElement['id'];
$currElThumbUrl = $currElement['thumbUrl'];
// 4. then proceed down the remaining array and compare the remaining indice's array's uid with the current one being explored
$artistCount=0;
// reset the second array $artistData02;
$artistData02 = array_values($artistData02);
foreach($artistData02 as $key02=>&$asset02){
// clear our temporary new element
unset($resultElement);
$resultElement=array();
// grab the new element to compare to.
// make sure it's not the same as the original
$newCurrElement = $artistData02[$key02];
$newCurrElUid = $newCurrElement['uid'];
$newCurrElid = $newCurrElement['id'];
$newCurrElThumbUrl = $newCurrElement['thumbUrl'];
// if I already compared this element, then skip it entirely
// We also don't want to compare the element to itself.
if ($key!=$key02){
// make sure the uids match
if($currElUid==$newCurrElUid){
// make sure the thumb URLs are different
if($currElThumbUrl!=$newCurrElThumbUrl){
// create the new merged element
// grab the filetype of $currElement
switch($currElement['filetype']){
case 1:
$resultElement['imageLge']=$currElement['publicUrl'];
$resultElement['imageSml']=$currElement['thumbUrl'];
break;
case 3:
$resultElement['song']=$currElement['publicUrl'];
break;
}
// then we compare the newCurrElement and add our information
switch($newCurrElement['filetype']){
case 1:
$resultElement['imageLge']=$newCurrElement['publicUrl'];
$resultElement['imageSml']=$newCurrElement['thumbUrl'];
break;
case 3:
$resultElement['song']=$newCurrElement['publicUrl'];
break;
}
// for the remaining values, we will pass as is
$resultElement['title']=$currElement['title'];
$resultElement['uid']=$currElement['uid'];
// take the resultant $resultElement and merge it to the main array (before $resultELement is recreated)
array_push($resultArr,$resultElement);
// this will reflow the elements, and change the indexing(so the echo merge statement will change). but comparisons will be reduced
unset($artistData[$key]);
$artistData = array_values($artistData);
unset($artistData02[$key02]);
$artistData02 = array_values($artistData02);
}else{
//echo "The thumbURLs are the same. skipping... <br />";
}
}else{
//echo "not the same uids. skipping... <br />";
}
}else{
//echo "this is the same element. skipping... <br />";
}
$artistCount++;
// end inner for...each loop
}
// 7. loop and check through the remaining elements in main array again.
}
/* end outer for each loop */
// add another element - the artist count at the end
$resultArr['artistCount']= $artistCount-1;
// build a JSON object that contains the artists, the total number
echo $resultArr;
again, any help is appreciated...
To answer your original question, this code will intake your masterArray and output your finalArray:
// sample array just for completeness
$masterArray = array(
array('id'=>'123', 'url'=>"http://xyz.com", 'data'=>"something", 'data2'=>"else"),
array('id'=>'123', 'url'=>"http://xyz.com", 'data'=>"something", 'data3'=>"baby"),
array('id'=>'456', 'url'=>"http://abc.com", 'data'=>"something", 'data2'=>"completely"),
array('id'=>'456', 'url'=>"http://abc.com", 'data'=>"something", 'data3'=>"different"),
array('id'=>'789', 'url'=>"http://def.com", 'data'=>"something", 'data2'=>"is not quite"),
array('id'=>'789', 'url'=>"http://def.com", 'data'=>"something", 'data3'=>"right")
);
// here's where the code actually begins
$finalArray = array();
foreach( $masterArray as $m )
{
if( !isset( $finalArray[$m['id']] ) )
$finalArray[$m['id']] = $m;
else
$finalArray[$m['id']] = array_merge( $finalArray[$m['id']], $m );
}
$finalArray = array_values( $finalArray );
If you var_dump $finalArray, it'll line up with what you wanted to get. This is matching based on id.
Your sample code I haven't taken the time to read thoroughly, is aggregating values based on id enough? If so, answer is above. ;)

PHP json_decode array cannot retrieve numerical index?

I have an array that is associative that I have decoded from a json json_decode second value true and looks like
Array (
[test] => Array
(
[start] => 1358766000
[end] => 1358775000
[start_day] => 21
[end_day] => 21
)
)
But for some reason when I do $array[0] I get null? How can I get the array by index? Not by key name?
array_values() will give you all the values in an array with keys renumbered from 0.
The first level of the array is not numerical, it's an associative array. You need to do:
$array['test']['start']
Alternatively, to get the first element:
reset($array);
$first_key = key($array);
print_r($array[$first_key]);
You could use current.
$first = current($array); // get the first element (in your case, 'test')
var_dump($first);
This is by design . . . your JSON used a key (apparently test), which contained a JSON object. The keys are preserved when you do a json_decode. You can't access by index, though you could loop through the whole thing using a foreach.
From your comment, it sounds like you want to access previous and next elements from an associative array. I don't know a way to do this directly, but a hackish way would be as follows:
$testArr = array('a'=>'10', 'b'=>'2', 'c'=>'4');
// get numeric index of the element of interest
$keys = array_keys($testArr);
$i = array_search('b', $keys);
// get key of next element
$nextElementKey = $keys[$i+1];
// next element value
$nextElementValue = $testArry[$nextElementKey];
// get key of previous element
$prevElementKey = $keys[$i-1];
// prev value
$[prevElementValue = $testArry[$prevElementKey];
You'd probably want to add some error checking around the previous and next key calculations to handle the first and last values.
If you don't care about the data in the key, Ignacio's solution using array_keys is much more efficient.

when two array having related value on same index of each array how to get relation when one array get sort ???PHP

how do i get the relation between the two array when both of them have values in some relation on the same indexes of both array for example,
i have retrieved "tagname" and "path" from one table of mysql and then i put these two column values in two arrays using loop so "array Tag[]" have vale "Introduction" and "array Path[]" have path value for introduction both values are on index "0" of there respected array and all data is collecten in "arrat Tag[]" and "array Path[]" in this manner after that i sort my "Tag" according to some other array using this code,
$sorted =array_intersection($some_other_array,$array Tag)
now how would i know the related path values for Tag as tag sorted ??
Hopes for your suggestions
from mysql/DB result set when you are creating array, create as
while($row = mysql_fetch_assoc($query)){
$array[$row['path']] = $row['tag'];
}
assuming your array as
$array['xyz'] = 'pqr';
$array['abc'] = 'wsx';
$array['poi'] = 'qaz';
$array['lkj'] = 'abc';
sort your array as per need based on tag or sorting methods available.
in this case instead of int index it will have key as path
sorting with tag also binds it with path.
after sorting your array (assuming sorting with first letter alphabates of tag name)
$array['lkj'] = 'abc';
$array['poi'] = 'qaz';
$array['xyz'] = 'pqr';
$array['abc'] = 'wsx';
so you can easily find path for your tag with foreach loop with key and value or with aray_keys if you want particular tag path and you know the tag value.
You need to combine those two arrays into associative arrays and then use asort() or uasort(), depending on particular sort scenario.

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