PHP create 1 array of 4 arrays ordered by index - php

I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?

I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);

You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array

<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.

do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}

Related

Set variable from an array in Laravel

The dump of the following array is:
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) }
As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).
I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
And the same with id :
$id1= $quest_all[0];
$id2= $quest_all[1];
Any help is appreciated.
Try as below:
One way is:
array_values($quest_all); will give you an array of all Ids
array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.
Other way, First get all qcounters only from collection:
$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
...
and so on
Then get all ids
$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
...
and so on
You can also use foreach to iterate through the result array.
To reset array keys, use array_values().
To get array keys, use array_keys():
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);
Or simply use foreach():
$keys = [];
$values = [];
foreach($quest_all as $key => $value){
$keys[] = $key;
$values[] = $value;
}
I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)
$quest_all = ...;
$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1
for ($i = 0; $i < $count; $i++) {
echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}
It would probably be easier to just have the 2 arrays:
$keys = array_keys($quest_all);
$values = array_values($quest_all);

PHP build array from variables

So I have a variable which I explode:
$values = explode ('|', $split);
This can contain any number of values from 1 to 10+
I have another big array let's call it $tree. I need to loop round the $values whilst building up an array based on the $tree variable.
E.g:
$newArray = $tree [$values [0]][$values [1]];
But this needs to be done dynamically based on the number of elements in the $values array.
Any ideas?
Thanks
Is this what you're trying to do?
$newArray = array();
foreach($values as $key => $val)
{
$newArray[] = $tree[$val][$values[$key + 1]];
}
You need a foreach loop that goes to every single value you have and then put them in the $tree array something like:
$newArray = array();
foreach($values as $index => $value)
{
$newArray[] = $tree[$value][$value[$index + 1]];
}
create a temporary array from $tree and iterate through the values getting each index:
$result = $tree;
foreach ($values as $val){
$result = $result[$val];
}
This way you go down one level deeper into $tree with each value supplied in $values, and $result holds the value stored in $tree at the point you have reached. For example if you have a navigation tree, $values would be the "breadcrumb" of the current navigation position, and $result is the remaining tree from this point downwards.
I think this is what you want. It goes through pairs of elements of $values, using them as the indexes into $tree to add to $newArray
$newArray = array();
for ($i = 0; $i < count(values); $i += 2) {
$newArray[] = $tree[$values[$i]][$values[$i+1]];
}
$values=array(0, 1, 3);
$tree=array("First", "Second", "Third", "Fourth");
$newarray=array();
for ($i=0; $i<count($values); $i++)
{
$newarray[]=$tree[$values[$i]];
}
echo(implode($newarray,", "));
Something like that what you were looking for?

Creating a ranked list from multiple arrays

I have 3 arrays that return a url,title,snippet and score from 3 different search engines, the score starts at 100 for the element in the array, the second 99 and so on, I'm trying to combine all 3 into one array. If the urls match from the different arrays I want to add the scores together and then delete the duplicate url. If there is no match between the urls then I just want to put this element into the combined array.
The final combined list should contain all distinct urls with its score,title and snippet, here are my array structures
googleArray
$x=0;
$score=100;
foreach ($js->items as $item)
{
$googleArray[$x]['link'] = ($item->{'link'});
$googleArray[$x]['title'] = ($item->{'title'});
$googleArray[$x]['snippet'] = ($item->{'snippet'});
$googleArray[$x]['score'] = $score--;
$x++;
}
blekkoArray
$score = 100;
foreach ($js->RESULT as $item)
{
$blekkoArray[$i]['url'] = ($item->{'url'});
$blekkoArray[$i]['title'] = ($item->{'url_title'});
$blekkoArray[$i]['snippet'] = ($item->{'snippet'});
$blekkoArray[$i]['score'] = $score--; // assign the $score value here
$i++;
}
bingArray
foreach($jsonObj->d->results as $value)
{ $i = 0;
$bingArray[]['Url'] = ($value->{'Url'});
$bingArray[]['Title'] = ($value->{'Title'});
$bingArray[]['Description'] = ($value->{'Description'});
$bingArray[]['score'] = $score--;
$i++;
}
Any help would be great, thanks in advance
This solution depends on a couple of things to work. First, the url and score keys need to be the same, i.e. all lower case and none that are "link." Secondly, the URLs have to be normalized, because they serve as the key for the array. If there are any differences in the URLs, they will show up more than once in the final array.
$merged = array_merge($googleArray, $blekkoArray);
$merged = array_merge($merged, $bingArray);
$combined = array();
foreach ($merged as $key => $value){
$score = (isset($combined[$value['url']]['score'])) ? $value['score'] + $combined[$value['url']]['score'] : $value['score'];
$combined[$value['url']] = $value;
$combined[$value['url']]['score'] = $score;
}
If you don't want to keep the URLs as the key, add this line:
$combined = array_values($combined);
If you want to sort the array by score, you can use usort:
usort($combined, function ($a, $b){
return $b['score'] - $a['score'];
});
print_r($combined);

Nested loops and array formation

Suppose that I start with an array that looks like:
$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));
For simplicity, assume that I have a rule that says: delete the first subarray and then delete the first elements of the remaining subarrays. This would yield the result:
$new_array = array(array(4,5), array(6,7))
Then assume I expand the problem to larger arrays like:
$array_2 = array(array(1,2,3,4), array(2,3,4,5), array(3,4,5,6), array(4,5,6,7));
I have the same rule here - delete first subarray and then delete first elements of the remaining subarrays. BUT this rule must be continued until the smallest subarray contains only two elements (as in the first example). So that in stage one of the process, my new array would look like:
$new_array_s1 = array(array(3,4,5), array(4,5,6), array(5,6,7));
But in the final stage, the completed array would look like:
$new_array_s2 = array(array(5,6), array(6,7));
For context, here is my code for the $array_1 example:
<?php
$array_1 = array(array(1,2,3), array(2,4,5), array(3,6,7));
$array_shell = $array_1;
unset($array_shell[0]);
$array_size = count($array_shell);
$i = 0;
$cofactor = array();
while($i < $array_size) {
$el_part_[$i] = $array_1[$i];
unset($el_part_[$i][0]);
$el_part_[$i] = array_values($el_part_[$i]);
array_push($cofactor, $el_part_[$i]);
++$i;
}
echo '<pre>',print_r($cofactor,1),'</pre>';
?>
My Question: How can I generalise this code to work for N sized arrays?
You don't need a complicated code .. Just loop and use array_shift
Example:
print_r(cleanUp($array_1));
Function
function cleanUp($array) {
array_shift($array);
foreach($array as $k => $var) {
is_array($var) && array_shift($array[$k]);
}
return $array;
}
See Live DEMO
$num = count($array_1);
for($i=0;$i<=$num;$i++)
{
if($i==0)
unset($array_1[$i]);
else unset($array_1[$i][0]);
}
Building off of Baba's answer, to work with N element arrays (assuming each array contains the same number of elements):
<?php
$array_1 = array(array(1,2,3,4), array(2,4,5,6), array(3,6,7,8));
$array = $array_1;
while(count($array[0]) > 2)
$array = cleanUp($array);
print_r($array);
function cleanUp($array) {
array_shift($array);
foreach($array as $k => $var) {
is_array($var) && array_shift($array[$k]);
}
return $array;
}
This will keep reducing until the sub-arrays have only 2 elements.
-Ken

Comparing arrays and giving out numbers depending on what value is in what array

This is more a kind of logical Question. Sometimes i think my Brain is not for programming ;(
What i want to do is.
IF array1 and array2 have the same values setup a new array with keyname to the value that the both array have in common and value = 3 OK i already got that.
Now i want:
IF a value is ONLY in array1 set new array value = 1
IF a value is ONLY in array2 set new array value = 2
$beidesgeht = array_intersect($acc_conf, $ano_conf);
foreach ( $beidesgeht as $be ) {
$fertig[ $be ] = 3;
}
I guess thats a easy one for you pros. ;)
After what you've got up there:
foreach ($acc_conf as $el) {
if (!isSet($fertig[$el])) {
$fertig[$el] = 1;
}
}
foreach ($ano_conf as $el) {
if (!isSet($fertig[$el])) {
$fertig[$el] = 2;
}
}

Categories