this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)
Related
I have an array of arrays consisting of date, login name, and time (length of time in ms). Here is what it vaguely looks like:
[0]=>
[0]=> "2015-09-06"
[1]=> "user1"
[2]=> "8947226"
[1]=>
[0]=> "2015-09-06"
[1]=> "user1"
[2]=> "6664923"
[2]=>
[0]=> "2015-09-24"
[1]=> "user2"
[2]=> "654654"
I'm trying to make it so that if the date and the login are both the same as another, it adds the time together. So it will look like:
[0]=>
[0]=> "2015-09-06"
[1]=> "user1"
[2]=> "15612149"
[1]=>
[0]=> "2015-09-24"
[1]=> "user2"
[2]=> "654654"
I think my main problem is how to search the array because they won't necessarily be in order by date or login, they're all random.
First I was doing this because I thought they would be in some sort of order:
if ($i != 0) {
if ($date == $bigArray[$prevIndex][0] && $login == $bigArray[$prevIndex][1]) {
$bigArray[$prevIndex][2] += $time;
} else {
array_push($bigArray, array($date, $login, $time));
$prevIndex++;
}
} else {
array_push($bigArray, array($date, $login, $time));
}
But that doesn't work since they are in a random order. I've tried to sort the array first as well, and that's not working.
There's a way to do it, but maybe it's not the best.
<?php
$arr = [];
$arr[0] = ["2015-09-26", "user1", "8947226"];
$arr[1] = ["2015-09-26", "user1", "6664923"];
$arr[2] = ["2015-09-24", "user2", "654654"];
// Variable to store the new values.
$arr2 = [];
// Scrolls through the array
foreach($arr as $ar) {
// Creates a key to identify date and login
$key = md5($ar[0].$ar[1]);
// Checks whether the value is already in the variable $arr2
if (isset($arr2[ $key ])) {
// If so, adds the values in ms
$arr2[ $key ][2] += $ar[2];
} else {
$arr2[ $key ] = $ar;
}
}
// Use the array_values to display only the values (without displaying the $key);
var_export( array_values($arr2) );
I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.
// First Array, which I have. The count and the content can change.
array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "5"
[2]=>
string(1) "8"
}
// Second Array, thats the goal.
array(1) {
[3]=>
array(1) {
[5]=>
array(1) {
[8]=>
array(0) {
}
}
}
}
This code will solve your problem:
$array = [3,5,8,9]; // your first array
$newArray = null;
foreach ($array as $value) {
if($newArray === null) {
$newArray[$value] = [];
$ref = &$newArray[$value];
}
else {
$ref[$value] = [];
$ref = &$ref[$value];
}
}
$newArray - holds the result you wanted
$array1=array(3,5,8);
$array2=array();
for($i=count($array1);$i>0;$i--){
$temp=array();
$temp[$array1[$i-1]]=$array2;
$array2=$temp;
}
$subject is the reference to the array you are currently in.
$array is the main root array that you obtain in the end.
$input is the input int array.
$subject = $array = [];
foreach($input as $key){
$subject[$key] = []; // create empty array
$subject =& $subject[$key]; // set reference to child
// Now $subject is the innermost array.
// Editing $subject will change the most nested value in $array
}
I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;
I have the following code:
foreach ($row as $item) {
if (!in_array($item['login_id'], $tmp)) {
$tmp[] = $item['brand'];
$tmp[] = $item['login_id'];
$tmp[] = $item['name'];
}
}
This provides the following output:
array(408) {
[0]=> string(4) "ABC"
[1]=> string(8) "r4ft6tg7"
[2]=> string(8) "Aberdeen"
[3]=> string(4) "ABC"
[4]=> string(8) "1ws3edft"
[5]=> string(18) "Birmingham Airport"
[6]=> string(4) "DDD"
[7]=> string(8) "bgt6yhnj"
[8]=> string(27) "Birmingham City"...}
I am trying to then loop through this array and add them to a dropdown using the following:
$a = 0;
$b = 1;
$c = 2;
foreach ($tmp as $value) {
echo "<option name='".$value[$a]."'
value='".$value[$b]."'>
".$value[$c]."
</option>";
$a=$a+3;
$b=$b+3;
$c=$c+3;
}
However the output is most odd:
<option name='I' value='b'>i</option>
The output I expected and need is:
<option name='ABC' value='r4ft6tg7'>Aberdeen</option>
Any suggestions, feedback on where I am going wrong would be appreciated.
I believe this is what you meant:
foreach ($row as $item) {
if (! array_key_exists($item['login_id'], $tmp)) {
$tmp[$item['login_id']] = array($item['brand'], $item['login_id'], $item['name']);
}
}
EDIT: Fixed index of $tmp above (and how to check for index).
Then your following code could work the same, omitting the increments of $a, $b, $c (and hence omitting those three variables altogether):
foreach ($tmp as $value) {
echo "<option name='".$value[0]."'
value='".$value[1]."'>
".$value[2]."
</option>";
}
You were mistakenly treating $tmp as both a one- and two-dimensional array. Actually setting it up to be a two-dimensional array resolves that. As pointed out in the comments, in your original code, $value was a string, and accessing an index of a string like you would an array yields the given character in the string.
Also, for clarity, you might consider making each subarray in $tmp an asssociative array.
E.g.
$tmp[$item['login_id']] = array('brand' => $item['brand'], ... and then accessing it accordingly in your latter foreach loop.
I have an array that groups different items by item type. I am grouping the result by category_id field. What I want is the output to be
item1 = 3
item2 = 2
My array looks like this if I do a var_dump()
array(2) {
["item1"]=>
array(3) {
[0]=>
string(1) "3"
[2]=>
string(1) "5"
[4]=>
string(1) "7"
}
["item2"]=>
array(2) {
[1]=>
string(1) "4"
[3]=>
string(1) "6"
}
}
Here is the code I am using:
$items = Item::where('order_id','=',$payload["orderId"])->get();
$itemsGrouped = [];
$count = 0;
foreach($items as $item){
$itemsGrouped[$item->category_id][$count] = $item->id;
$count++;
}
foreach($itemsGrouped as $grp){
echo key($itemsGrouped).'='.count($grp).'<br>';
};
And here is what I am currently getting. The count is working but not the $itemsGrouped key. It is duplicated.
item2=3<br>item2=2<br>
Change your code as below
foreach($itemsGrouped as $key => $grp){
echo $key.'='.count($grp).'<br>';
};
In order to use key() function, you need to traverse the array using next/current function
foreach($itemsGrouped as $key => $grp){
echo $key.'='.count($grp).'<br>';
};
key() function returns the current element's key, which is defined by an array's internal pointer. Obviously it always points to the last element.
$myarray = "Your array";
$count = array(); // create an empty array
foreach($myarray as $arr) {
foreach($arr as $a) {
$key = array_keys($a);
$count[$key[0]]++;
}
}
print_r($count);