print the array when it is exploded - php

In the below code i am getting the output
Array ( [0] => 1 [1] => 2 )
but the expected output is
Array ( [0] => 1 [1] => 2 [2] => 3) Array ( [0] => 1 [1] => 2 )
why is it always executing the second if condition? although the first condition is also true.
this is the code I have tried
<?php
$test_arr=array();
$temp_option_arr=array();
$option_arr=array();
$options_array_val = Array ( 0 => "animals:1", 1 => "animals:2", 2 => "animals:3", 3 => "birds:1", 4 => "birds:2" );
foreach($options_array_val as $options_val)
{
$search_filter = explode(":", $options_val);
print_r($search_filter);
if(!in_array($search_filter[0],$option_arr))
{
array_push($temp_option_arr,$search_filter[1]);
array_push($option_arr,$search_filter[0]);
$temp_option_arr=array();
}
array_push($temp_option_arr,$search_filter[1]);
}
$test_arr[$search_filter[0]]=$temp_option_arr;
$find_species = array();
if(!empty($test_arr['animals']))
{
$find_species = $test_arr['animals'];
print_r($find_species);
}
if(!empty($test_arr['birds']))
{
$find_species = $test_arr['birds'];
print_r($find_species);
}
?>

The line
$test_arr[$search_filter[0]]=$temp_option_arr;
is out of the foreach scope, therefore it only sets the array for the birds and not for the animals, so you need to move it one line upper.
Also, you assign temp_option_arr to a value
array_push($temp_option_arr,$search_filter[1]);
then set it back to empty array without using it
$temp_option_arr=array();
You can remove the first one I guess

You clear $temp_option_arr in the first part of your code, so it will have nothing that concerns animals by the time you exit the first loop.
But instead of using all these different arrays, just build an associative array keyed by the species (animals, birds, ...), and with as values the arrays of IDs (1, 2, 3, ... i.e., the parts after the :):
foreach($options_array_val as $options_val) {
list($species, $id) = explode(":", $options_val);
$option_arr[$species][] = $id;
}
After this loop the structure of $option_arr is this:
Array (
"animals" => Array (1, 2, 3)
"birds" => Array (1, 2)
)
I think you can do what you want with that. For instance to only get the animals:
$option_arr["animals"]
which is:
Array (1, 2, 3)

Related

How do I make an array without using array_count_values()?

I have an array, $arrayName = array(1,2,1,3,4,3,2,5);. I want the result as:
Array (
[1] => 2
[2] => 2
[3] => 2
[4] => 1
[5] => 1
)
Without using array_count_values(), what is the logic behind array_count_values()?
This method will only loop each value once compared to other methods posted here.
Instead of looping the full array I get unique values and count them with array_keys and count.
$arrayName = array(1,2,1,3,4,3,2,5);
$values = array_unique($arrayName);
Foreach($values as $val){
$count[$val] = count(array_keys($arrayName, $val));
}
Var_dump($count);
https://3v4l.org/EGGJq
In your example I think my method may actually be slower than looping the full array, but if this was a large array there may be a benefit of not looping the full array.
The best solution is to use array_count_values function. That counts frequency of values in an array.
See this - http://php.net/manual/en/function.array-count-values.php
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
However, If you don't want to use that function, you can do an ugly way of for loop.
$arrayName = array(1,2,1,3,4,3,2,5);
$resultArray = array();
foreach($arrayName as $value) {
$resultArray[$value] = isset($resultArray[$value]) ? $resultArray[$value] + 1 : 1;
}
print_r($resultArray); // Array ( [1] => 2 [2] => 2 [3] => 2 [4] => 1 [5] => 1 )
Counting frequencies of array elements

check if value explode in array is duplicated with another explode value

hello try to find the duplicated value in array i have array like that
$array = array('1%2','3%4','1%2',1%3);
so i want to find duplicated 2 after % so i used explode inside foreach
foreach($array as $value){
$s = explode('%',$value);
if($s[1] == $s[1]){
echo 'there are duplicated 2';
}
}
so i want $s[1] check if value after % in array is duplicated
is there anyway to do that
You will need to collect the right side values as you loop through them and check for duplicates. I am accessing the strings' right side values via their "offset" [2]. When found, you can exit the loop with a break.
Code: (Demo)
$array=['1%2','3%4','1%2','1%3'];
$kept=[];
foreach($array as $i=>$v){
if(in_array($v[2],$kept)){
echo "Element (index $i) containing $v has duplicate right side value.";
break;
}
$kept[]=$v[2];
}
Output:
Element (index 2) containing 1%2 has duplicate right side value.
If you want to search for all element that end with %2, you can use preg_grep().
Code:
$search=2;
$array=['1%2','1%3','1%4','3%2','5%2'];
var_export(preg_grep("/%{$search}$/",$array));
Output:
array (
0 => '1%2',
3 => '3%2',
4 => '5%2',
)
Or without regex, it will require more function calls:
$search=2;
$array=['21%2','1%3','2%22','1%4','3%21','5%2'];
var_export(array_filter($array,function($v)use($search){return strpos($v,"%$search")+2===strlen($v);}));
Output:
array (
0 => '21%2',
5 => '5%2',
)
...[deep breath] Here is attempted answer #4...
Code:
$array=['1%2','1%3','1%4','3%2','5%2'];
foreach($array as $v){
$grouped[explode('%',$v)[1]][]=$v; // use right side number as key
}
var_export($grouped);
Output:
array (
2 =>
array (
0 => '1%2',
1 => '3%2',
2 => '5%2',
),
3 =>
array (
0 => '1%3',
),
4 =>
array (
0 => '1%4',
),
)
If you want to count the right side values in the array:
$array=['1%2','1%3','1%4','3%2','5%2'];
$array=preg_replace('/\d+%/','',$array); // strip the left-size and % from elements
var_export(array_count_values($array)); // count occurrences
Output:
// [right side values] => [counts]
array (
2 => 3,
3 => 1,
4 => 1,
)

combine multi-dimensional array on value from JSON

I have 2 api end points that load JSON data...
1. subject matter experts
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
)
...
)
people database
Array
(
[0] => Array
(
[Id] => 1
[Name] => Joe
[Office] => New York
)
....
)
I'd like to pass both functions into an array, specify to merge on [matter.PersonId] => [people.Id] so the returned array would become
Array
(
[0] => Array
(
[ExpertiseId] => 1
[IndustryId] => 1
[PersonId] => 3
[Id] => 1
[Name] => Joe
[Office] => New York
)
...
)
You have to iterate over both arrays and reorganize the data in such a way that merging can happen. In practice that means rekeying the first array by PersonId and the second by Id; this is very easy to do with array_column:
$matter = array_column($matter, null, 'PersonId');
$people = array_column($people, null, 'Id');
At this point only a simple task is left: merging the items (arrays) that share the same key in both $matter and $people.
In a perfect world that would be an one-liner with array_merge_recursive, but that function does not actually merge arrays that have integer keys like these (the ids we used as keys are integers). So a little standard iteration is in order: pick one of the arrays and merge its contents with the other:
foreach ($people as $id => $data) {
// If there's a guarantee that both arrays will definitely have the same
// set of keys (ids) so that $matter[$id] is guaranteed to exist,
// you can also use the simpler: $matter[$id] += $data
$matter[$id] = isset($matter[id]) ? $matter[$id] + $data : $data;
}
...and now $matter has all the data merged together.
Try array_merge()
$newArray = array_merge(first_array, second_array);

How do I insert a value in between two keys in an array using php?

I have an array with 3 values:
$b = array('A','B','C');
This is what the original array looks like:
Array ( [0] => A [1] => B [2] => C )
I would like to insert a specific value(For example, the letter 'X') at the position between the first and second key, and then shift all the values following it down one. So in effect it would become the 2nd value, the 2nd would become the 3rd, and the 3rd would become the 4th.
This is what the array should look like afterward:
Array ( [0] => A [1] => X [2] => B [3] => C )
How do I insert a value in between two keys in an array using php?
array_splice() is your friend:
$arr = array('A','B','C');
array_splice($arr, 1, 0, array('X'));
// $arr is now array('A','X','B','C')
This function manipulates arrays and is usually used to truncate an array. However, if you "tell it" to delete zero items ($length == 0), you can insert one or more items at the specified index.
Note that the value(s) to be inserted have to be passed in an array.
There is a way without the use of array_splice. It is simpler, however, more dirty.
Here is your code:
$arr = array('A', 'B', 'C');
$arr['1.5'] = 'X'; // '1.5' should be a string
ksort($arr);
The output:
Array
(
[0] => A
[1] => B
[1.5] => X
[2] => C
)

If value exists in one PHP array, add value to second array

I have two PHP arrays. One contains a group name and another contains a pay wage value.
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 3 );
This means there are four employees on the schedule. Two are assigned to group 1, another to group 4 and the last to group 3.
The second array is as follows:
$tot_wages_array = Array ( [0] => 500 [1] => 44 [2] => 80 [3] => 11.25 );
This is a sample array of each employee's wage. Both arrays are constructed in order as values are added in a mysql while loop as it pulls the info from the database.
Later on down the line, I combine the two arrays to get one array where the key is the group number and the value is the total wages for that group:
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
This works like a charm EXCEPT for when more than one employee is assigned to the same group. These arrays are built in a mysql while loop as it loops through each employee's info:
array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array
Instead of just pushing the data to the array, I need to do this... I know the english but I don't know how to code it:
If $emp_data['group_id'] exists as value in $group_wages_array, add nothing to this array but get the key. Add $totemp_wages_sch to $tot_wages_array where key = group_wages_array key
I know it sounds more like an SQL query but I have to keep the keys and values in order so that they can be combined later in the page. If I can get this to work right, The arrays shown in the example would be:
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 3 );
$tot_wages_array = Array ( [0] => 580 [1] => 44 [2] => 11.25 );
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
$combined_group_wages = Array ( [1] => 580 [4] => 44 [3] => 11.25 );
...I've got to make this work using PHP. Any ideas?
I came up with a solution based on a combination of two of the answers submitted below. Here it is if it can help someone:
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] += $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
array_push($tot_wages_array, $totemp_wages_sch);
}
This should do it:
$group_wages_array = array(1, 4, 1, 3);
$tot_wages_array = array(500, 44, 80, 11.25);
$combined_group_wages = array();
for ($i=0; $i<count($group_wages_array); $i++) {
$group = $group_wages_array[$i];
if (array_key_exists($group_wages_array[$group], $combined_group_wages)) {
$combined_group_wages[$group] += $tot_wages_array[$i];
} else {
$combined_group_wages[$group] = $tot_wages_array[$i];
}
}
print_r($combined_group_wages);
Yields:
Array
(
[1] => 580
[4] => 44
[3] => 11.25
)
But I recommend that you just switch to using objects to better represent your data.
If I could see the entirety of the code that would help a lot, but here's your English converted to php. Show me more code and I can perfect it, until then try this ->
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] = $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
}

Categories