Change key of an array PHP - php

I have this array $theme_name
Array
(
[0] => template0
[1] => template1
[2] => template2
[3] => template3
[4] => template4
[5] => template5
[6] => template6
)
and this other array that has the same lenght $theme_info
Array
(
[0] => my template n 00
[1] => my template n 01
[2] => my template n 02
[3] => my template n 03
[4] => my template n 04
[5] => my template n 05
[6] => my template n 06
)
Basically what I want is to have this array :
Array
(
[template0] => my template n 00
[template1] => my template n 01
[template2] => my template n 02
[template3] => my template n 03
[template4] => my template n 04
[template5] => my template n 05
[template6] => my template n 06
)
Why this won't work ?
foreach ($themes_info as $key => $value) {
include($value['directory']) ;
$theme_info[] = $info;
$theme_name[] = $value['name'];
}
foreach ($theme_name as $key => $value) {
$value = $theme_info[$key];
}
FYI $themes_info have all the themes with names and directories emplacement.

Use array_combine():
$result = array_combine($theme_name, $theme_info);
Demo

You can do this far easier in PHP. Just like this:
for ($i = 0; $i < count($themes_info); $i++) {
include($value['directory']);
$theme_info[] = $info;
$theme_name["someKey$i"] = $value['name'];
}
And replace someKey with your prefered key for that array. Or for any other array for that matter.

Related

Array - Select the sub children id's from an array

I have this array built from a function that sorts allowed or valid url slugs and their ids into another array. I can call the current category id by passing the url slug to the category. Now I need to get the children category ids (if any) so i can call the appropriate items from the database for display purpose.
Heres an example of the array:
Array (
[radios] => 1
[radios/motorola] => 2
[radios/motorola/handheld] => 3
[radios/motorola/mobile] => 4
[radios/icom] => 5
[radios/icom/handheld] => 6
[radios/icom/mobile] => 7
[radios/mics-and-speakers] => 8
[radios/mounts] => 9
[radios/radio-other] => 10
[misc] => 11
[misc/led] => 12
[phones] => 13
[phones/samsung] => 14
[phones/lg] => 15
[phones/motorola] => 16
[phones/huawei] => 17
[phones/blackberry] => 18
[phones/flip] => 19
[boosters] => 20
[boosters/standalone] => 21
[boosters/indoor-antenna] => 22
[boosters/outdoor-antenna] => 23
[boosters/connections] => 24
[accessories] => 25
[accessories/cases] => 26
[accessories/other] => 27
[internet] => 28
[internet/fusion] => 29
[internet/point-to-point] => 30
[internet/hotspots] => 31
[internet/gateways] => 32
[internet/switches] => 33
[cameras] => 34
[cameras/complete-kits] => 35
[cameras/additional-cameras] => 36
[cameras/other] => 37
);
As you can see, each result points to the category ID of that group. If i visit the following url:
http://example.com/store/cameras
I can print out that THE PATH CURRENTLY IS: 34 which is correct. Since It has children under it, I also need their ID's and the ID's of any of their children, etc etc. That way on radios, i can show ALL of the sub category items, and on radios/motorola i am only showing the Motorola based items and its children, and such down the line.
If there an easy way, using this array I have now, to sort the children (if any) all the way down and get back just their id's (preferably in a new array) for showing database items?
You might want to create a function like this to filter your array,
function filterArray($array, $term) {
$pattern = "/\b" . str_replace($term, '/', '\/') . "\b/i";
foreach($array as $key => $value) {
if(preg_match($pattern, $key)) {
/* Following condition makes sure that your search
will match starting from the beginning. */
if (stripos(trim($key), $term) === 0){
$filtred[] = $value;
}
}
}
}
Then call the above function with the $array and your search $term.
filterArray($array, 'radios') will give you this,
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )
filterArray($array, 'radios/motorola') will give you this,
Array ( [0] => 2 [1] => 3 [2] => 4 )
And so on.. I hope this helps.
You can maybe try double layer array, so that you can store values like this,
Array (
[name] => John
[surname] => Smith
[contact] => Array (
[address] => 18 Maple Street
[number] => 555 477 77 77
)
)
This way if you need to print something from "contact" you can use a loop and print all childs of contact field.

Multi dimensional php array not working

Hi I'm trying to create a multi dimensional array but having problems. I have a multi dimensional array that I'm trying to push other arrays onto. The arrays are created and pushed within an array.
$initialChild = $selectorDetailsArray[0];
$selectorDetailsMultiDimArray = array();
$multiDimHoldArray = array();
for($r=0;$r<count($selectorDetailsArray);$r+=3){
echo "Test vars are ".$selectorDetailsArray[$r]." : ".$initialChild."<br> ";
if(intval($selectorDetailsArray[$r]) == intval($initialChild)){
echo"<br> r is ".$r."<br>";
array_push($multiDimHoldArray,$selectorDetailsArray[$r+1],$selectorDetailsArray[$r+2]);
echo"<br> values are ".$selectorDetailsArray[$r+1]." ".$selectorDetailsArray[$r+2]."<br>";
print "<pre>";
print_r($multiDimHoldArray);
print "</pre>";
}else{
array_push($selectorDetailsMultiDimArray,$multiDimHoldArray);
$multiDimHoldArray = array();
echo "initial child is ".$initialChild."<br>";
$initialChild = $selectorDetailsArray[$r];
echo "initial child after change is ".$initialChild."<br>";
}
}
print "<pre>";
print_r($selectorDetailsMultiDimArray);
print "</pre>";
exit;
output is like this
Array
(
[0] => 65
[1] => 1
[2] => 0
[3] => 65
[4] => 29
[5] => 64
[6] => 66
[7] => 1
[8] => 69
[9] => 66
[10] => 29
[11] => 65
)
Test vars are 65 : 65
r is 0
values are 1 0
Array
(
[0] => 1
[1] => 0
)
Test vars are 65 : 65
r is 3
values are 29 64
Array
(
[0] => 1
[1] => 0
[2] => 29
[3] => 64
)
Test vars are 66 : 65
initial child is 65
initial child after change is 66
Test vars are 66 : 66
r is 9
values are 29 65
Array
(
[0] => 29
[1] => 65
)
Array
(
[0] => Array
(
[0] => 1
[1] => 0
[2] => 29
[3] => 64
)
)
I can't get it to push the second array - I must be missing something?
I've tried everything I can think of but can't figure out why the second array (that's been created) isn't pushed onto the multi dimensional array.
Any help would be great
Not sure what the overall purpose of the code is for "exactly" but I do understand the results you were trying to get, and I also understand why it was not working. I have commented my code so you should be able to see what it is doing. I created an array in the code to start with, but I presume it would work with whatever array you are getting even though you are not showing how it was generated.
$selectorDetailsArray = Array(65,1,0,65,29,64,66,1,69,66,29,65);
$initialChild = $selectorDetailsArray[0];
$selectorDetailsMultiDimArray = array();
$multiDimHoldArray = array();
$loopstrings = array(" :: 1st loop :: "," :: 2nd loop :: "," :: 3rd loop :: "," :: 4th loop :: ");
$loop = 0;
$dim = 0;
for($r=0;$r<count($selectorDetailsArray);$r+=3){
echo "<br>START".$loopstrings[$loop]."<br>";
echo "Test vars are ".$selectorDetailsArray[$r]." : ".$initialChild."<br> ";
if(intval($selectorDetailsArray[$r]) == intval($initialChild)){
echo"<br> r is ".$r."<br>";
array_push($multiDimHoldArray,$selectorDetailsArray[$r+1],$selectorDetailsArray[$r+2]);
echo"<br> values are ".$selectorDetailsArray[$r+1]." ".$selectorDetailsArray[$r+2]."<br>";
}else{
array_push($selectorDetailsMultiDimArray,$multiDimHoldArray);
$multiDimHoldArray = array();
// This needs to be here because the "if" is not run during this loop...
array_push($multiDimHoldArray,$selectorDetailsArray[$r+1],$selectorDetailsArray[$r+2]);
echo "initial child is ".$initialChild."<br>";
$initialChild = $selectorDetailsArray[$r];
echo "initial child after change is ".$initialChild." -- ($ r = $r)<br>";
}
echo "<br>END".$loopstrings[$loop++]."<br>";
}
// We push one last time since it successfully pushed twice more in the "if" but never ran the "else" a final time...
array_push($selectorDetailsMultiDimArray,$multiDimHoldArray);
echo "<br>";
echo "<br>BEGIN OUTPUT<br>";
print "<pre>";
print_r($selectorDetailsArray);
print_r($multiDimHoldArray);
print_r($selectorDetailsMultiDimArray);
print "</pre>";
This is the output that my code generates. I have added a few lines to make it readable, and also output all of the arrays at the end:
START :: 1st loop ::
Test vars are 65 : 65
r is 0
values are 1 0
END :: 1st loop ::
START :: 2nd loop ::
Test vars are 65 : 65
r is 3
values are 29 64
END :: 2nd loop ::
START :: 3rd loop ::
Test vars are 66 : 65
initial child is 65
initial child after change is 66 -- ($ r = 6)
END :: 3rd loop ::
START :: 4th loop ::
Test vars are 66 : 66
r is 9
values are 29 65
END :: 4th loop ::
BEGIN OUTPUT
Array
(
[0] => 65
[1] => 1
[2] => 0
[3] => 65
[4] => 29
[5] => 64
[6] => 66
[7] => 1
[8] => 69
[9] => 66
[10] => 29
[11] => 65
)
Array
(
[0] => 1
[1] => 69
[2] => 29
[3] => 65
)
Array
(
[0] => Array
(
[0] => 1
[1] => 0
[2] => 29
[3] => 64
)
[1] => Array
(
[0] => 1
[1] => 69
[2] => 29
[3] => 65
)
)

Increment a variable with numeric and uppercase letter

Can you tell me how I can increment a variable in PHP from 00 to ZZ ?
With A5, 8R, GG...
I tried this but it's just for letter :
for($i="AA"; $i<="ZZ" AND strlen($i)<=2; $i++)
Thank you
i created a little snippet that should demonstrate how you can use range($start,$end) to create what you are looking for
<?php
//create an array with all values from 0-9 and A-Z
$range = array_merge(range("0","9"),range("A","Z"));
//create counter-aray
$counter = array();
//loop through the range
foreach($range as $value1){
foreach($range as $value2){
$counter[] = $value1.$value2;
}
}
//show the counter
print_r($counter);
?>
result:
Array
(
[0] => 00
[1] => 01
[2] => 02
[3] => 03
[4] => 04
[5] => 05
[6] => 06
[7] => 07
[8] => 08
[9] => 09
[10] => 0A
[11] => 0B
[12] => 0C
[13] => 0D
[14] => 0E
[15] => 0F
[16] => 0G
[17] => 0H
[18] => 0I
[19] => 0J
[20] => 0K
[21] => 0L
.....many more values follow here
)
feel free to ask questions if you need further explaination
It actually sounds as if you are trying to add numbers in base 36. Since PHP can convert between bases, you could add the numbers in base 10 then convert into base 36.
for($i = 0; $i <= base_convert("zz", 36, 10); $i++) {
echo(str_pad(strtoupper(base_convert($i, 10, 36)), 2, "0", STR_PAD_LEFT) . PHP_EOL);
}
$i is an integer in base 10 that will loop from 0 to 1295. (zz in base 10.)
base_convert converts $i from base 10 to base 36.
strtoupper converts the resulting string to uppercase so you get AA instead of aa.
str_pad will add leading 0s to convert values such as 0 to 00.

Insert element into order position of array?

All values of array $A are string the same length.
$A = Array
(
[0] => 03
[1] => 04
[2] => 05
[3] => 06
// [4] => 07 // "07" before "04" position
[4] => 04
[5] => 05
[6] => 06
// [8] => 07 // "07" before "08" position
[7] => 08
[8] => 03
[9] => 04
[10] => 05
[11] => 06
[12] => 07 // it is existing
[13] => 08
) ;
I want to Insert the "07" element if it is not existing before "04" or "08" position.start from position 1
So It will be after changed
$A = Array
(
[0] => 03
[1] => 04
[2] => 05
[3] => 06
[4] => 07 // just appended
[5] => 04
[6] => 05
[7] => 06
[8] => 07 // just append
[9] => 08
[10] => 03
[11] => 04
[12] => 05
[13] => 06
[14] => 07
[15] => 08
) ;
Anybody know how to do this ,help me please?
There would be "prettier" ways to do this but, as intended...
iterate the array
if the current value is equal to 7 minus 1 you will insert a new value there
create a function "insert_into_array" that:
a) Splits your array in two (look at array_chunk)
b) POPs your element to the end of the first array (array_pop)
c) merges your two arrays back (array_merge)
I've abstained from writing any code as this is probably homework and, writing code, even if you're not really deep thinking the problem will push you a long way to passing the exam...
not the most beautiful solution, but should do the job:
$b = array();
for($i=0;$i<count($A);$i++){
$b[] = $A[$i];
if(($i<count($A) - 1) && ($A[$i+1]<$A[$i] || ($A[$i+1] == '08')) && $A[$i] < '07')
$b[] = '07';
}
var_dump($b);
First, find the gaps in your array, that is the positions where there's 06 but not a following 07:
$positions = array();
foreach ($A as $k => $v) {
if (isset($last) && $last != $v - 1 && $last == '06') {
$positions[] = $k;
}
$last = $v;
}
Then, insert them:
$count = 0;
foreach ($positions as $pos) {
array_splice($A, $pos + ($count++), 0, '07');
}
That's it.
//make sure the array is numeric:
$A = array_values($A);
foreach(array('04','08') as $search){
$positions = array_keys($A,$search);
rsort($positions);
foreach($positions as $key){
if($key==0 || $A[$key-1] != '07'){
array_splice($A,$key,0,'O7');
}
}
}
In 2017, I've found 2 beautiful methods that is part of nette\utils package.
Arrays::insertBefore()
Arrays::insertAfter()
They do job perfectly!
Just run:
composer require nette/utils
and use Arrays class or inspire in their code.

Find missing numbers in array

I'm trying to find each missing number in an array like the following.
Array (
[0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8
[8] => 9 [9] => 10 [10] => 11 [11] => 12 [12] => 13 [13] => 14 [14] => 15
[15] => 16 [16] => 17 [17] => 18 [18] => 19 [19] => 20 [20] => 21 [21] => 22
[22] => 23 [23] => 24 [24] => 25 [25] => 26 [26] => 27 [27] => 28 [28] => 29
[29] => 30 [30] => 31 [31] => 32 [32] => 33 [33] => 34 [34] => 35 [35] => 36
[36] => 37 [37] => 38 [38] => 39 [39] => 40 [40] => 41 [41] => 42 [42] => 43
[43] => 44 [44] => 45 [45] => 46 [46] => 47 [47] => 48 [48] => 49 [49] => 50
[50] => 51 [51] => 52 [52] => 53 [53] => 54 [54] => 55 [55] => 56 [56] => 57
[57] => 58 [58] => 59 [59] => 60 [60] => 61 [61] => 62 [62] => 63 [63] => 64
[64] => 67 [65] => 68 [66] => 69
)
The numbers 65,66 are missing in this particular array.
My question how do I figure out which numbers are missing with the help of PHP. Specifically what I need to find out is the lowest missing number.
Why: Because then I can assign that number to a member as an id.
You can make use of array_diff and range functions as:
// given array. 3 and 6 are missing.
$arr1 = array(1,2,4,5,7);
// construct a new array:1,2....max(given array).
$arr2 = range(1,max($arr1));
// use array_diff to get the missing elements
$missing = array_diff($arr2,$arr1); // (3,6)
I'm assuming the number is the element, not the key, of the array. I'm also assuming that the numbers start from 1, not 0.
$Expected = 1;
foreach ($InputArray as $Key => $Number)
{
if ($Expected != $Number)
{
break;
}
$Expected++;
}
echo $Number;
For big sorted arrays of unique numbers, you can binary search the array for either the lowest or highest unused number. Cost=Log2N. Example: 65536 items can be searched in 16 loops since
if ( arr[hi] - arr[lo] > hi - lo )
... there are unused numbers in that range ...
So (I don't know PHP, but it can be translated...):
lo = first entry index
hi = last entry index
if ( arr[hi] - arr[lo] == hi - lo )
return arr[hi]+1; // no gaps so return highest + 1
do
{
mid = (lo + hi) / 2;
if ( arr[mid] - arr[lo] > mid - lo ) // there is a gap in the bottom half somewhere
hi = mid; // search the bottom half
else
lo = mid; // search the top half
} while ( hi > lo + 1 ); // search until 2 left
return arr[lo]+1;
If given input is not in sorted order and size of input is very large then we can use following logic in any programming language:
Algorithm
bring smaller chunk into memory from large input
initialize three variables say min = 0, max = 0 and missingIds = []
scan smaller chunked input from left to right
if scannedValue found in missingIds
then,
pop scannedValue from missingIds
go to next value;
If scanned value is near to min
then,
find all the missing numbers between scannedValue and min, push into missingIds
min = scannedValue;
Else if scanned value is near to max
then,
find all the missing numbers between scannedValue and max, push into missingIds
max = scannedValue;
repeat above steps until large input scanned from left to right
Example in PHP
<?php
$largeInput = [40,41,42,43,44,45,1,2,3,4,5,6,7,8,9,10,11,12,13,14,35,36,37,38,39,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,67,68,69,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34];
$missingIds = [];
$min = 0;
$max = 0;
$chunkSize = 10;
$chunkNo = 0;
$currentInput = array_slice($largeInput, $chunkNo, $chunkSize);
while(count($currentInput) > 0) {
foreach($currentInput as $id) {
if(in_array($id,$missingIds)) {
$missingIds = array_diff($missingIds,[$id]);
continue;
}
if($id <= $min) {
$distMin = $min - $id;
if($distMin > 2) {
$tempArr = range($id+1,$min-1);
$missingIds = array_merge($missingIds, $tempArr);
$tempArr = [];
} else if ($distMin > 1) {
$tempArr = [$id+1];
$missingIds = array_merge($missingIds, $tempArr);
$tempArr = [];
}
$min = $id;
} else if ($id >= $max){
$distMax = $id - $max;
if($distMax > 2) {
$tempArr = range($max+1,$id-1);
$missingIds = array_merge($missingIds, $tempArr);
$tempArr = [];
} else if ($distMax > 1) {
$tempArr = [$max+1];
$missingIds = array_merge($missingIds, $tempArr);
$tempArr = [];
}
$max = $id;
}
}
$chunkNo++;
$currentInput = array_slice($largeInput, $chunkNo, $chunkSize);
}
print_r($missingIds);
//$idArrayMissing = array([0] => 1, [1] => 2, [2] => 4, [3] => 5, [4] => 6, [5] => 7);
$idArrayMissing = array(1, 2, 4, 5, 6, 7);
//$idArrayFull = array([0] => 1, [1] => 2, [2] => 3, [3] => 4, [4] => 5, [5] => 6);
$idArrayFull = array(1, 2, 3, 4, 5, 6);
function gap($arr)
{
while (list($k, $v) = each($arr))
if ($k != ($v-1))
return $k;
return -1;
}
print "ok:" . gap($idArrayMissing) . "<br/>\n";
print "full:" . gap($idArrayFull) . "<br/>\n";
The return of the gap function can be 2 values:
-1 could indicate that the array has been traversed and there are no free slots or
$k+1 which could indicate that the first free slot is on the end of the array.
It can also be done easily by using in_array() function like this:
// lets say $InputArray has all the data
// lets declare a variable which we will search inside the $InputArray array and lets initialize it with either 0 or 1 or with the minimum value found inside $InputArray
$start_counting = 1;
$max_value = count($InputArray);
if (!(in_array($start_counting, $InputArray)))
{
echo "Value: ".$start_counting." is missing!"."<br>" ;
}
else{
if($start_counting <= $max_value -1)
{$start_counting++;}
}
else if($start_counting > $max_value -1)
{
echo "All missing numbers printed!"
}
}

Categories