How to get the values inside an array? - php

$playerId= array();
$playerId[] = intval($row['Id']);
$allrounders[] = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
rsort($allrounders);
$sliceAr = array_slice($allrounders,0,5);
foreach($sliceAr as $allroundK){
echo $allrounders[]['Id']."<br/>";
}
Question:
In the above array how to get the values of the Id Key accordingly? It takes all the player scores and organizes that with his ID and sorts it descending order. It takes the 1st 5 results. I need the Ids of those.

Inside the foreach loop, $allroundK is the item of your array. In this case, it's the array with weight and id. So:
foreach($sliceAr as $allroundK) {
echo $allroundK['Id']."<br />";
}

Do
echo $allrounders[0]['Id'][0];
Since you have set the array in this manner
$allrounders[] = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
Here $allrounders[] also means that an array so the elements Weight and Id will be added in the [0th] element of the array $allrounders
If you want to get rid of [0] just set the array like this
$allrounders = array(
'Weight'=>$fullTotal,
'Id'=>$playerId
);
And now you can access the Id like
echo $allrounders['Id'][0];
EDIT:
In your case it will work as
foreach($sliceAr as $allroundK){
echo $allroundK['Id'][0]."<br/>";
}
or
foreach($sliceAr as $allroundK){
foreach($allroundK['Id'][0] as $allroundJ){
echo $allroundJ."<br/>";
}
}

Related

How to place the array returned from a MySql count to a variable

PHP Code:
$results = $wpdb->get_results('SELECT COUNT(*) AS "total" FROM mydbfield');
echo $total;
echo total;
print "<pre>";
print_r($results);
print "</pre>"
Results array:
Array
(
[0] => stdClass Object
(
[total] => 16876
)
I want my answer to be like = 16876 not all the other stuff.
With this, my total for this table is $total. And it will print 16876.
Do not want to see all that array stuff printed. I have spent a lot of time studying php in the W3.
One way is with extract() function. In your case, assuming $results always return an array with length equal to 1
$results = (array) reset($results); // or $results[0] instead of reset, then cast to array
extract($results); // Extract results
echo $total; // You can now use $total which returns 16876
print $results[0]['total'];
get_results returns a set of rows. By definition you will only get one row on a SELECT COUNT(*), so $results[0] gives you the one-and-only-one row and $results[0]['total'] returns the desired value.
Based on the above, you could try:
$total = $results[0]->total;
echo $total;
Or
$resultObj = current($results);
Which enables you to do:
$total = $resultObj->total;
echo $total;
I would suggest you read something like https://www.w3schools.com/PhP/php_arrays.asp, along with http://php.net/manual/en/language.oop5.basic.php to learn more about how results objects are returned in an array

Search multi-dimesional array and return specific value

Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.
Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:
$data = '13,4,3|65,1,1|27,3,2';
$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);
I'm able to return any value using
echo $return_2d_array[1][0];
But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).
You can loop through the dataset building an array that you can use to search:
$data = '13,4,3|65,1,1|27,3,2';
$data_explode = explode("|",$data); // make array with comma values
foreach($data_explode as $data_set){
$data_set_explode = explode(",",$data_set); // make an array for the comma values
$new_key = $data_set_explode[0]; // assign the key
unset($data_set_explode[0]); // now unset the key so it's not a value..
$remaining_vals = array_values($data_set_explode); // use array_values to reset the keys
$my_data[$new_key] = $remaining_vals; // the array!
}
if(isset($my_data[13])){ // if the array key exists
echo $my_data[13][0];
// echo $my_data[13][1];
// woohoo!
}
Here it is in action: http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d
Run one more foreach loop like this:
$value_to_search = 27;
foreach($return_2d_array as $array){
if($array[0] == $value_to_search){
echo $array[1]; // will give 3
break;
}
}
Here's the live demo.

How to store string variables in php array

$matrix=array($_SESSION['review_buffer_name'],$_SESSION['review_buffer_mail'],$_SESSION['review_buffer_comment']);
The above line of code is inside WHILE loop So that it stores more than one record of array.Is it correct way to store records?. And how can we access each record and value of matrix?
$matrix should store multiple row of arrays... The problem is when i'm accessing $matrix[2] then it is giving second value of array... instead of second record of array
You can try it:
//Before while loop declare the array variable
$matrix = array();
While(your condition){
$matrix[] = array(
$_SESSION['review_buffer_name'],
$_SESSION['review_buffer_mail'],
$_SESSION['review_buffer_comment']
);
}
//To access array:
print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0][0]; //echo single data that first row's first data
Or you can set index as name like:
//Before while loop declare the array variable
$matrix = array();
While(your condition){
$matrix[] = array(
'review_buffer_name'=>$_SESSION['review_buffer_name'],
'review_buffer_mail'=>$_SESSION['review_buffer_mail'],
'review_buffer_comment'=>$_SESSION['review_buffer_comment']
);
}
//Then access array:
print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0]['review_buffer_name']; // first row's first data

fetch data from model that is called in loop

I have a controller function in CodeIgniter that looks like this:
$perm = $this->job_m->getIdByGroup();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
What I need to do is list the data in the result in the view, but I get only the last value while using this method. How can I pass all the results to the view?
Store it in an array. Like this:
foreach($perm as $pe=>$p){
$result[] = $this->job_m->getDatapermission($p['id']);
}
Because $result is not an array...
try this:
$result=array();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[] = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
Note:
My answer uses a counter to enable the display of a single group result when needed.
Guessing from your need to loop and display the value of $result, possibly, it is an array or object returned by $query->result(). Things could be a bit complex.
Example: if $perm is an array of 5 items( or groups), the counter assigns keys 1 - 5 instead of 0 - 4 as would [] which could be misleading. Using the first view example, you could choose to display a single group value if you wants by passing it via a url segment. Making the code more flexible and reusable. E.g. You want to show just returns for group 2, in my example, $result[2] would do just that else next code runs. See my comments in the code.
$perm = $this->job_m->getIdByGroup();
$counter = 1;
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[$counter] = $this->job_m->getDatapermission($pId);
$counter++;
}
$data['permission'] = $result;
As mentioned above Note:
I Added a Counter or Key so you target specific level. If the groups are:
Men, Women, Boys, Girls, Children; you'd know women is group two(2) If you desire to display values for just that group, you don't need to rewrite the code below. Just pass the group key would be as easy as telling it by their sequence. To display all the loop without restrictions, use the second view example. To use both, use an if statement for that.
###To access it you could target a specific level like
if(isset($permission)){
foreach($permission[2] as $key => $value){
echo $value->columnname;
}
###To get all results:
foreach($permission as $array){
foreach($array as $key => $value){
echo $value->columnname;
}
}
}

Breaking a MultiDimensional Array into a Single Dimension

I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);

Categories