How can I get the numeric value from an array? - php

I have this following segment in my array.
[genres] => Array
(
[0] => Adventure
[1] => Drama
[2] => Game
[3] => Harem
[4] => Martial Arts
[5] => Seinen
)
I am trying to return each of those elements separately.
foreach($t['genres'] as $tag=>$value) {
// I don't know what to do from here
}
Can someone help me on how I can print each unique value?

genres is an associative array meaning that the key will only give you the index point of that value. Your values are of type String, not numerical values.
$genres = ['Adventure', 'Drama', 'Game', 'Harem', 'Martial Arts', 'Seinen'];
So in this case, at index point 0 (arrays start at 0), we will get Adventure.
[0] => Adventure
To get these values out of the array one by one you can do this:
foreach($genres as $_genre) {
echo $_genre;
}
To get these values and/or keys from the array one by one you can do this:
foreach($genres as $_key => $_genre) {
echo "Index: {$_key} - Value: {$_genre}"
}
Keys are numerical values, they mark the point of the value in that array. For example, if we wanted to get Game from the array:
[2] => Game
We can see that it has an index of 2 and can be called like:
echo $genres[2];

Related

Why PHP lose item value of array?

I have the array with values:
$array1 = array('Boss', 'Lentin', 'Endless');
print_r ($array);
The result will be:
Array ( [0] => Boss [1] => Lentin [2] => Endless
It's ok.
But, if I add two elements to this array with a keys, the "Boss" element will be lost.
$array2 = array("1"=>'Doctor','Boss', 2=>'Lynx', 'Lentin', 'Endless');
print_r ($array2);
The result will be:
Array ( [1] => Doctor [2] => Lynx [3] => Lentin [4] => Endless )
//Where is "BOSS"???
Why?
When php create the array, set Doctor in index 1 and Boss in index 2, but 2=>'Lynx' cause php overwrite index 2 and set Lynx in it.
You can set it after setted index or use index for it. For example like
$array2 = array("1"=>'Doctor', 2=>'Lynx', 'Boss', 'Lentin', 'Endless');
// or
$array2 = array("1"=>'Doctor', 2=>'Boss', 3=>'Lynx', 'Lentin', 'Endless');
When $array is being created, 'Boss' will first be stored in index 2 (Array([2] =>'Boss') which is later overwritten by 'Lynx'
Your issue is index keys
$array2 = array("1"=>'Doctor','Boss', 2=>'Lynx', 'Lentin', 'Endless');
print_r ($array2);
This is because, on index 1 it is already doctor, boss will be second, which will be replaced by Lynx which have same index of 2 where boss will be replaced.
I hope I am clear.
This is expected behaviour from php (see http://php.net/manual/en/language.types.array.php#example-57). In case you need all the values in the array and don't need to work with keys, I recommend to use array_push($array $value). Otherwise you should add all the values with their keys and remember that for PHP 1 and "1" and true are the same values so they will overwrite each other.
array() is a construct with dynamic arguments representing literal arrays. The assignment of the given values to the array structure is done sequentially i.e. one by one from left to right. In your example:
Doctor is assigned to index 1.
Boss is assigned to index 2.
Lynx overwrites index 2.
Lentin and Endless are assigned to index 3 and 4 respectively.
hey #Weltkind first of all i suggest you to read
"http://php.net/manual/en/language.types.array.php",
now come to your answer In php the array key can be string or integer and if you do not mention the key then
default integer is set and the value of next array key is depending on the previous array integer key means
next array key = previous integer key + 1;
In PHP array the same key value will override by the same key
Now lets understand with your array2:
<?php
$array2 = array("1"=>'Doctor','Boss', 2=>'Lynx', 'Lentin', 'Endless');
1) as you started your array with key "1" so the
so for 1st key value is [1] => 'Doctor'
current array like: array([1] => 'Doctor')
now next key = previous integer key(that is 1) + 1 = 2;
2) for 2nd key value is [2] => 'BOSS'
current array like: array([1] => 'Doctor', [2] => 'BOSS')
3) next key = previous integer key(that is 2) + 1 = 3 it will carry
to next key but as next key is [2] => 'Lynx' as you mentioned so at
key [2] the value will be override by value 'BOSS' to 'Lynx'; current
array like : array([1] => 'Doctor', [2] => 'Lynx')
Now the next key we have is [3]
4) for next value the key is [3] => 'Lentin'
current array like : array([1] => 'Doctor', [2] => 'Lynx', [3] =>
'Lentin');
now next key = previous integer key(that is 3) + 1 = 4;
5) for next value the key is [4] => 'Endless'
current array like : array([1] => 'Doctor', [2] => 'Lynx', [3] =>
'Lentin', [4] => 'Endless');
and that is why the final array is like below :
array(
[1] => 'Doctor',
[2] => 'Lynx',
[3] => 'Lentin',
[4] => 'Endless'
);

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);

php - multidimensional array regex search and print out partial array to look at structure

I have this array structure, it is stored in a variable $xxx
Array
(
[xyz] => Array
(
[1] => 3
[0] => s
)
[d2s] => Array
(
[a] => 96
[d] => 4
)
...
)
It is a long array, and I don't want to out put the whole thing, how do print only the first 5 (1st dimension) values along with the 2nd dimension values?
Secondly, if I want this array to contain only alphabets in the FIRST dimension, how do I either delete values that don't match that requirement or retain values that match the requirement? so that my final array would be
Array
(
[xyz] => Array
(
[1] => 3
[0] => s
)
...
)
TIA
To output only the first 5 elements, use array_slice:
array_slice($arr, 0, 5)
To remove any elements whose index contains non-alpha characters.
foreach ($arr AS $index => $value) {
// Remove the element if the index contains non-alpha characters
if (preg_match('/[^A-Za-z]/', $index))
unset($arr[$index]);
}
Check it out in action.

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']);
}

Get key values from multidimensional array

I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.
The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.
I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.
Array (
[is_error] => 0
[version] => 3
[count] => 2
[values] => Array (
[556053] => Array (
[contact_id] => 556053
[contact_type] => Individual
[first_name] => Brian
[last_name] => YYY
[contact_is_deleted] => 0
)
[596945] => Array (
[contact_id] => 596945
[contact_type] => Individual
[first_name] => Brian
[last_name] => XXX
[contact_is_deleted] => 0
)
)
)
I've looked at the following post, but it seems to only address the situation where the array indices are sequential.
Multidimensional array - how to get specific values from sub-array
Any ideas?
Brian
You are correct in your assumption. You could do something like this:
foreach($array['values'] as $key => $values) {
print $values['contact_id'];
}
That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.
Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:
$a['values'][556053]['contact_id']
and here:
$a['values'][596945]['contact_id']
So if there's no additional structure in your array, then this loop is probably what you want:
foreach ($a['values'] as $toplevel_id => $record_data) {
print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}
foreach($array['values'] as $sub_arr){
echo $sub_arr['contact_id'];
}

Categories