foreach integers into array - php

since im newbie i have a question
well i have $nUserID where store user's id's and is like
int(1)
int(2)
int(1)
and in $nAuctionID i have items id and they are like
int(150022)
int(150022)
int(150031)
i need put it in 1 array and make it like
array (
[1] => 150022
[2] => 120022,150031
)
which user which item id watch
how to do that ?
i though should use foreach , but i cant imagine how will looks
start with
$u[] = $nUserID;
$i[] = $nAuctionID;`

Grouping them by user ID, the following should result in what you're looking for.
$usersWatching = array();
// The following results in:
// array(1 => array(150022, 150023), 2 => array(150022))
// Which should be way more useful.
foreach ($nUserID as $i => $userID)
{
if (!isset($usersWatching[$userID]))
$usersWatching[$userID] = array();
$usersWatching[$userID][] = $nAuctionID[$i];
}
// To get the comma-separated version, do this:
$usersWatching = array_map(function ($value) {
return implode(',', $value);
}, $usersWatching);

this will work :
$arr = array();
foreach( $nUserID as $key=>$value)
{
$arr[$value] = $nAuctionID[$key] ;
}
print_r($arr);

Most confusingly worded question EVA!
$outputArray = array();
for ($i=0; $i< count($nUserID); $i++) {
$outputArray[$nUserID[$i]] = $nAuctionID[$i];
}
echo "<pre>";
print_r($outputArray);
That is what I got from your question..

Related

Getting values to compare from a Explode Array of Strings

I have this string that I'm Getting from a Mysql Result:
Result1:
1/test3&2/test4&
Then, I have some ID from another mysql Result like this:
Result2:
$id = $row['id'];
Then I'm using an Explode in order to separate Result1:. Like I'm Getting this:
$nota3 = explode("&", $nota);
1/test3&
2/test4&
Now, I'm doing I'm using a foreach and then using another explode to separate the string by "/" delimiter.
foreach ($nota3 as $key) {
$nota4 = explode("/", $key);
}
The Result of this its something like this (for the firsts foreach iteration):
array(2) {
[0]=>
string(1) "1"
[1]=>
string(5) "test3"
}
Ok, So I cannot Compare nota4[0] with $id from Result2:
Things that I've Tried:
Using if and verify every type, converts nota4[0] a $id to string
Try to use in_Array
Try to use strcmp($var1, $var2)
I'm Missing something but I really dont know what.
Also, when I tried I cant put nota4[0] into a html String like
$nota5= nota4[0];
echo "<p id='mic' class='text-dark bg-warning'>".$nota5."</p>";
Maybe its something silly but I tried everything without success.
You can make sure both are strings and trim and use a strict operator - even if it seems they are already that
$result1 = "1/test3&2/test4&";
$result2 = "1";
$id = trim((string) $result2);
foreach ($nota3 as $key) {
$nota4 = explode("/", $key);
if (trim((string) $nota4[0]) === $id) {
//...
}
}
Here's another way to go about it. This will set up $result1 (or you can rename it) to become an associative array of key/value pairs, allowing you to loop through and compare a value like $result2 with a key id in the $result1 array. Example link included.
<?php
$result1 = "1/test3&2/test4&";
$result2 = "1";
$result1 = array_map(function ($a) {
$tmp = explode("/", $a);
return array('id' => $tmp[0],'name' => $tmp[1]);
}, array_filter(explode("&", $result1)));
print_r($result1);
now to get $result2
foreach ($result1 as $item) {
if ($item['id'] == $result2) {
// $value
}
}
Output of result1
[0] => Array
(
[id] => 1
[name] => test3
)
[1] => Array
(
[id] => 2
[name] => test4
)
https://www.tehplayground.com/1436vTBhUOYx9MNX

Parse formatted strings containing 3 delimiters to create multiple flat arrays

I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).

Explode a string into bidimensional array

Excuse me if this question was already solved. I've searched trough the site and couldn't find an answer.
I'm trying to build a bi-dimensional array from a string. The string has this structure:
$workers="name1:age1/name2:age2/name3:age3"
The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".
I know the basics about the explode function:
$array=explode("separator","$string");
But I have no idea how to face this to make it bidimensional. Any help would be appreciated.
Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.
$row = 0;
foreach (explode("/", $workers) as $substring) {
$col = 0;
foreach (explode(":", $substring) as $value) {
$array[$row][$col] = $value;
$col++;
}
$row++;
}
$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");
foreach ($workers as $worker) {
$worker = explode(':', $worker);
$array[$worker[0]] = $worker[1];
}
Try this code:
<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
$new_arr[]=explode(':',$value);
}
?>
The quick solution is
$results = [];
$data = explode("/", $workers);
foreach ($data as $row) {
$line = explode(":", $row);
$results[] = [$line[0], $line[1]];
}
You could also use array_walk with a custom function which does the second level split for you.
This is another approach, not multidimensional:
parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);
Shorter in PHP >= 5.4.0:
parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);
yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...
$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);
output:
Array
(
[name] => Array
(
[1] => age1
[2] => age2
[3] => age3
)
)

PHP Extract and count first elements of each element in multidimensional array

I have this array in php,
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
I can easily loop through it and extract all the first entries of each array like this:
foreach($mainArray as $w => $n) {
$whatever = $mainArray[$w][0];
}
I'm trying to count how many entries are the same in the first element of each array, and have a result of something like:
apple (2)
samsung (2)
microsoft (1)
nokia (1)
I'm just not sure what is the correct way to do this.
Thank you in advance.
print_r(
array_count_values(
array_map('array_shift', $mainArray)
)
);
Output (Demo):
Array
(
[apple] => 2
[samsung] => 2
[microsoft] => 1
[nokia] => 1
)
So even I am a big fan of foreach, why did I not use it here?
First of all, to count values in an array, in PHP we have array_count_values. It does the job for us.
So the only problem left was to get all the first items into an array to count them with array_count_values. That is a typical mapping job, and I like mapping, too, next to foreach so I tried if array_map together with array_shift worked - and it did.
However you might want to look for a function called array_column. It's not yet available with PHP itself, but as PHP code in another answer:
$counts = array_count_values(array_column($mainArray, 0));
$count = array();
foreach($mainArray as $array) {
$first = $array[0];
if(!isset($count[$first])) $count[$first] = 0;
$count[$first]++;
}
print_r($count);
Collect every first element of the deep arrays by pushing them into a new array ($result in my example) and then call array_count_values() on that array. Like so:
$mainArray = array(
array("apple","two", "grren"),
array("samsung","five", "red"),
array("microsoft","one","gray"),
array("apple","nine", "blue"),
array("samsung","ten", "white"),
array("nokia","seven", "yellow")
);
$result = array();
foreach( $mainArray as $k => $v )
{
// let's continue if $v is not an array or is empty
if( !is_array( $v ) || empty( $v ) ) continue;
$result[] = $v[ 0 ];
}
var_dump( array_count_values( $result ) );
You can loop through the $mainArray to build a full array/list of values and then use array_count_values() on that:
$firstElements = array();
foreach ($mainArray as $arr) {
$firstElements[] = $arr[0];
}
$counts = array_count_values($firstElements);
Another option would be to loop through $mainArray and insert the value as an index for an array (if it doesn't already exist) and then increment it each time (this will do the same thing as array_count_values() in the end):
$counts = array();
foreach ($mainArray as $arr) {
if (!isset($counts[$arr[0]])) $counts[$arr[0]] = 0;
$counts[$arr[0]]++;
}
You can do it just like this:
foreach($mainArray as $n) {
$count[$n[0]] = isset($count[$n[0]]) ? $count[$n[0]]++ : 1;
}
var_dump($count); //should give you something like
/*
array(4) {
["apple"]=>
int(2)
["samsung"]=>
int(2)
["microsoft"]=>
int(1)
["nokia"]=>
int(1)
}
*/

Trying to modify an array to avoid overlapping key-value pairs using PHP

I have an array that looks like this:
Array([5258]=>5274,
[5261]=>5281,
[5264]=>5287,
[5271]=>5289 );
I want to modify this array so that any overlaps in key value pairs are removed.
To elaborate, the first key value pair should become [5258]=>5289, because the numerical value of the each of the rest of the keys is less than 5274, the original value corresponding to the first key.
What would be the best way to do this using PHP? I'll appreciate some pointers on this.
Thanks.
EDIT: Just a reword to the background for my question:
If there's an array like this:
Array([10]=>12
[11]=>15
[16]=>20)
I want to derive another array/modify the same array to get
Array([10]=>15
[16]=>20)
I hope this makes things clearer.
Is this a game of guess the actual question?
This is my answer to what I think the question is:
$arr = Array(
5258=>5274,
5261=>5281,
5264=>5287,
1=>100,
50=>70,
40=>130,
5271=>5289
);
ksort($arr);
$out = array();
$start = null;
foreach ( $arr as $from=>$to )
{
if ( $start === null )
{
$start = $from;
$end = $to;
} else {
if ( $from < $end )
{
$end = max($end,$to);
} else {
$out[$start] = $end;
$start = null;
}
}
}
if ( $start !== null ) $out[$start] = $end;
print_r($out);
output:
Array
(
[1] => 130
[5261] => 5289
)
<?php
$arr = array(5258=>5274,
5261=>5281,
5264=>5287,
5271=>5289 ,
5301=>5400);
ksort($arr);
$new = array();
$currentkey = reset(array_keys($arr));
$currentvalue = reset($arr);
foreach($arr as $key=>$value){
if($key > $currentvalue){
$new[$currentkey] = $currentvalue;
$currentkey = $key;
}
$currentvalue = max($currentvalue,$value);
}
$new[$currentkey] = $currentvalue;
var_dump($new);
?>
Take a look at usort() but I'm not quite sure how it works. It's a bit black magic for me. At a guess, make a function which compares the key values and orders the array like that.
Or you could tinker with array_merge()
Apologies for a waffling answer, I don't quite understand your question, or the criteria for how you want to merge/sort your array

Categories