Loop not working with assosiative array Php - php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);

I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';

I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

Related

Create PHP Variables dynamically in foreach loop

I am just trying to create PHP variables dynamically. below is the code I have tried.
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
while
$BrickTerritorys is
[1] => stdClass Object
(
[id] => 119
[TerritoryID] => HYD-2-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 40.00
[BPCode] => bp00066
[GroupCode] => CMD
)
[2] => stdClass Object
(
[id] => 36330
[TerritoryID] => HYD-1-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 60.00
[BPCode] => bp00066
[GroupCode] => CMD
)
When I print in the last, nothing gets printed. Any help is much appreciated, please.
Thanks in advance
${"T$index"} as well as ${"Weightage$index"}
you don't need the dot,or you can use ${'T' . $index}. look at the dot. it's not addition operation while it in "". following this code:
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
Try changing those lines like this:
${"T$index"}= $BrickTerritory->TerritoryID;
${"Weightage$index"} = $BrickTerritory->Weightage;
In your code ${"$T.$index"} $T is searching for variable, and you should get undefined variable $T, so you have to remove $ sign, if you want to have T1, T2 variables.
After that, ${"'Weightage'.$index"}, the apostrophes between Weightage means your variable will look like 'Weightage'.1, 'Weightage'.2.. and etc.
This can be done a few different ways without variable variables AND produce a completely dynamic outcome.
Here's one: (Demo)
$array = (array)$BrickTerritorys; // cast as array
$tids = array_column($array, 'TerritoryID'); // isolate column data
$was = array_column($array, 'Weightage'); // isolate column data
$merged = array_merge($tids, $was); // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
echo str_repeat('-', $i) , $v; // increase hyphens on each iteration starting from 0
}
Output: (notice, no hardcoded echo)
HYD-2-CMD-HYD-1-CMD--40.00---60.00

How to output different levels of an array

As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand

Pull out values from multidimensional associative array

I have a multidimensional array which Im trying to pull all the values of a certain key and assign it to a variable.
This is the array:
Array
(
[I_would_not_know_the_name_of_this_key] => Array
(
[interval] => 3600
[display] => Once Hourly
)
[nor_this_one] => Array
(
[interval] => 43200
[display] => Twice Daily
)
[nor_this_one] => Array
(
[interval] => 86400
[display] => Once Daily
)
)
I want to always get the [display] value even when I do not know what the upper level value is.
function which contains the array above, more schedules can be added which is why I said I would not always know the top level key: https://codex.wordpress.org/Function_Reference/wp_get_schedules
My code so far:
$active_cron_schedules = wp_get_schedules(); //this is the
foreach ($active_cron_schedules as $key => $value) {
echo $key;
}
?>
This outputs for example: 'I_would_not_know_the_name_of_this_key', 'nor_this_one', 'nor_this_one', I need to get in deeper.
Arrays have always given me a run for my money in PHP can't figure out how to loop through it :(
Thank you
I think what you are trying to do will be solved with a foreach() loop or array_column() depending on your version of php. The variable part is hard to answer because you have not given an example of what you would be doing with the variable. A common mistake is to overwrite the variable in a loop, but if all you want are all the display values (or any other key), try:
function getValByKey($array, $getKey = 'display')
{
$new = array();
foreach($array as $arr) {
if(empty($arr[$getKey]))
continue;
$new[] = $arr[$getKey];
}
return $new;
}
$result = array(
'key1'=> array('interval'=>1,'display'=>'1d'),
'key2'=> array('interval'=>2,'display'=>'2d'),
'key3'=> array('interval'=>3,'display'=>'3d')
);
// To use
$display = getValByKey($result);
print_r($display);
// Array column has the same basic function, but
// Only available in PHP 5 >= 5.5.0, PHP 7
$display = array_column($result,'display');
print_r($display);
Both give you:
Array
(
[0] => 1d
[1] => 2d
[2] => 3d
)
whatever is the key, you dont even need to know it in a foreach.
here is a sample. $key can be anything. you just have to check for it s interval child element.
$interval_list = array();
foreach ($array as $key => $el) {
if (isset($el['interval'])) {
$interval_list[] = $el['interval'];
}
}

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

PHP Array_unique value error in while loop

This is my PHP script for getting plan
This is my table
plan
3|6
6|12
3|12
and
<?php
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal=explode("|",$t_data['plan']);
print_r(array_unique($arrayVal));
}
?>
and I got the result is
Array ( [0] => 3 [1] => 6 ) Array ( [0] => 6 [1] => 12 )
Here I want 3,6,12 only. What is the problem in my script
before your while loop add this line:
$arrayVal = array();
and replace $arrayVal=explode("|",$t_data['plan']); with $arrayVal=array_merge($arrayVal, explode("|",$t_data['plan']));
$tenure="SELECT plan from ".TABLE_TYBO_EMI_GATEWAY;
$t_result=dbQuery($tenure);
$arrayVal = array();
while($t_data=mysql_fetch_assoc($t_result))
{
$arrayVal = array_merge($arrayVal, explode("|",$t_data['plan']));
}
print_r(array_unique($arrayVal));
Note: When using array_merge with associated arrays, it will overwrite values for same keys, but when using numeric keys array_merge will not overwrite them instead append as new values.

Categories