PHP: how to add array index then cut into several array? - php

I have make many changes but still cannot figure out.
i have an array let say: [1,2,3,4,5,6,7,8,9,10]
i just want to ask how to add this array until index 2 and continued add for rest array then divide them by 2 array each.
input : [1,2,3,4,5,6,7,8,9,10 ];
process : [1+2+3, 4+5+6, 7+8+9, 10]
output i need : [6,15,24,10]
then i want to cut this array into 2
last output : [[6,5],[24,10]]
Thanks

Your code will be:
$data = range(1,10);
$result = array_chunk(array_map('array_sum', array_chunk($data, 3)), 2);
-please, read array functions manual

Something like this?
<?php
$array = range(1, 10);
$array = array_chunk($array, 3);
$array = array_map('array_sum', $array);
$array = array_chunk($array, 2);
print_r(
$array
);
/*
Array
(
[0] => Array
(
[0] => 6
[1] => 15
)
[1] => Array
(
[0] => 24
[1] => 10
)
)
*/

I think you can use a for cycle to sum what you need then store result in new array. Another solution is using array merge. When you've done the trick you can create a multidimensional array to get the result like [[6,5],[24,10]].
Hope it helps

Can't really see what you are getting at from the question, but I think PHP's array_chunk command may be your friend on this, http://www.php.net/manual/en/function.array-chunk.php
this will allow you to split the array into chunks of 3 (or any number) of elements with last element containing the remainder (in this case 1 element)

Related

Get value from different arrays

I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here

How to cut array into two

I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

array_intersect a variable amount of arrays

I am creating a faceted search, and I'm am trying to use array_intersect to compare the arrays and find the inputs that match.
The problem is that I will have a variable amount of arrays at anytime depending on what filters the user has selected:
$array_1, $array_2, $array_3 etc...
How do I create an array_intersect function that is dynamic in this sense?
This is what I've tried:
$next_array = 0;
for($i = 0; $i < $array_count; $i++) {
$next_array++;
if ($i == 0) {
$full_array = ${array_.$i};
} else {
if(!empty(${cvp_array.$next_array})) {
$full_array = array_intersect($full_array, ${cvp_array_.$next_array});
}
}
}
------------- EDIT -------------
I'll try to narrow down my goal a bit more:
If the user clicks three filters, this results in three arrays being created with each having individual results:
Array_1 ( [0] => 2, [1] => 4, [2] => 6 )
Array_2 ( [0] => 1, [1] => 4, [2] => 6 )
Array_3 ( [0] => 6, [1] => 7, [2] => 8 )
I need code that will find the number that is in ALL of the arrays. And if there is no common number then it would end as false or something. In the case above, I'd need it to retrieve 6. If it was only the first two arrays, it would return 4 and 6.
Try this:
$fullArray = array($array1, $array2, $array3...);
call_user_func_array('array_intersect', $fullArray);
One can use:
$intersect = array_intersect(...$fullArray);
First of all, turn those arrays into an array of arrays. Then you can use array_reduce combined with array_intersect to reduce a variable amount of arrays down to one.
You can turn those array to a single array named $total_array by using array_combine(),
then use array_intersect($full_array, $total_array). I hope this useful

How to delete element and also shift the $key in array

I have an array looks like
Array
(
[0] => 1213059
[1] => 1213063
[2] =>
[3] =>
[4] => 1213072
)
I would like to make it as following:
Array
(
[0] => 1213059
[1] => 1213063
[2] => 1213072
)
Is there anyone can help me?
Many thanks
Use array_filter
Check demo here:
array_values(array_filter($your_array)); to keep your keys numerically .
array_filter will remove all elements that evaluate to false:
$array = array_filter($array);
I don't think answers above give correct fields order, as it was asked. If you only want to remove some fields from array and leave keys order untouched you could do it with
array_filter($arr) or with unset($arr[$i])
But if you want to get new order of keys, so there is no "holes", in above example to set key 4 to key 2 as keys 2 and 3 are unset, you have to use
ksort($arr)
Here is a complete example:
$arr=array(1,1,3,2,0);
print_r($arr);
echo '<br>';
unset($arr[2]);
ksort($arr);
print_r($arr);
$arr=array_values($arr);#EDITED
ksort($arr) knows not to sort array as it should, so just in case add $arr=array_values($arr); on the end #EDITED
PHP reference of ksort() is on link.
You may use this workaround.
Define this function somewhere:
function removeArrElement($inArr, $elementNr) {
for ($i = $elementNr; $i < count($inArr) - 1; $i++) {
$inArr[$i] = $inArr[$i + 1];
}
unset($inArr[count($inArr) - 1]);
return $inArr;
}
And then, when you want to remove the specific element from $yourArray, do this:
$yourArray = removeArrElement($yourArray, $nthElement);
I feel it's not the most efficient way to do this, but it works fine.

Categories