how to get associative array value in php? - php

I have an associative array in php that looks like this
incSched={"62":"10878","63":"10878","64":"10878","65":"10878","66":"28416","67":"28416","68":"28416","69":"28416","70":"28416"}
How do I access the value for "62"?
I've tried
$amt = $incSched[$j];
$amt = $incSched["$j"];
$amt = $incSched[strval($j)];
they all return an empty string.
Here is the full loop so you can see what $j is:
$startAge = 53;
for ($i=0; $i<count($incTableIds); $i++) {
$tableId = $incTableIds[$i];
for ($j=$startAge; $j<101; $j++) {
$incSched = $incomeSchedules[$tableId];
echo "incSched=" .json_encode($incSched) ."<br>";
$amt = $incSched["$j"];
if ($amt == "") $amt = 0;
if ($j>$startAge) $amt = $incSchedules[$tableId][$j-1]; //use previous value
echo "Income: tableId=$tableId, age=$j, amt=$amt<br>";
$incSchedules[$tableId][$j] = $amt;
}
}
Here is the output when the loop hits 62
Income: tableId=1, age=62, amt=0
amt should be 10878, not 0. Any ideas?

You are using the JSON Format but without the quotes. In order to decode the JSON format, you'll have to convert your value into a JSON string. Try this below code:
// $incSched = '[{"62":"10878"},{"63":"10878"},{"64":"10878"},{"65":"10878"},{"66":"28416"},{"67":"28416"},{"68":"28416"},{"69":"28416"},{"70":"28416"}]';
$incSched = '{"62":"10878","63":"10878","64":"10878","65":"10878","66":"28416","67":"28416","68":"28416","69":"28416","70":"28416"}';
$incSched = json_decode($incSched, true);
foreach ($incSched as $key => $value) {
echo $key . '=>'. $value . '<br />';
}
In the above, I have given you both the valid formats of JSON.
Hope this helps.

Related

Add new data in foreach loop multidimensional array

I try to add new data in a multidimensional array for each loop, but it wont work.
This shows the values in my array:
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
$klanten['newData'] = 'test';
}
}
With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.
I also tried to use this, AFTER the script above:
foreach ($klanten as &$item ){
$item['newData'] = 'test';
}
That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?
Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
// $klanten['newData'] = 'test'; // instead of this
$klanten[$key]['newData'] = 'test'; // do this
}
}
This will save each and every value of newData index according to its key in $klanten array.

how to sort an array in descending order in php

Newly-entered products are displayed in the last row. If there is a large amount, it is difficult to see at the bottom. How can I change the new display to the top. Thank you!
$barcodes_ary = explode(',', $barcodes);
$barcodes_hash = array ();
foreach ($barcodes_ary as $b) {
if (array_key_exists($b, $barcodes_hash)) {
$barcodes_hash[$b] += 1;
} else {
$barcodes_hash[$b] = 1;
}
}
foreach ($barcodes_hash as $b => $amount) {
if ($barcodes_ary == array(''))continue;
$ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
if ( count($ary) == 0 ) {
continue;
}
$pid = $ary[0]['ProductID'];
$pn = $ary[0]['ProductName'];
$unit = $ary[0]['UnitID'];
$ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
$unit = $ary2[0]['UnitName'];
?>
<TR>
<TD><? echo "$pn"; ?></TD>
<TD>
<INPUT TYPE=hidden NAME=productid<?=$pid?> VALUE='<?=$pid?>'>
<?
$candidates = array();
for($i=1; $i <= DropDownMaxValue; $i++) {
$candidates[]=$i;
}
//update
I use another way to solve the problem. Just display the same product.
function push_barcode() {
// alert('barcode pushing');
b = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
bs.value = b.value;
} else { // ?? 111,333,444,... ???
bs.value = b.value;
}
}
Okay, you should be able to get the count using the keys values returned in reverse in brackets with the array.
Try the following and see if it works for you...
$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
//--> concatenate the values into a variable for display
$output .= $ProductName[$count];
//--> or push the reversed values back into an array
$product_name[$i] = $ProductName[$count];
//--> $product_name should now hold your values in reverse use a foreach
// use a foreach to display values in your table
$count--;
$i++;
}

Get last two items of json_decode results with PHP

The following code works and pulls all the images in from the json file.
$content = file_get_contents('URL');
$json = json_decode($content, true);
foreach($json['format'] as $item) {
echo '<img src="' . $item['picture'] . '">';
}
Is there a way that I can have it only grab the last two pictures.
Yes, there is a way.
$result = array_slice($json['format'], -2);
Have a try.
Use this:
$numItems = count(foreach($json['format']);
$i = 0;
foreach($json['format'] as $item) {
if(++$i === $numItems-1) {
result1 = $json['format'][$i]
echo "first picture!";
} if(++$i === $numItems) {
result2 = $json['format'][$i]
echo "second picture!";
}
}
And result1 and result2 is your pictures
You can reverse the order of the array, run it backwards in your foreach loop, grab the first two then break.
$reversed = array_reverse($json);
$counter = 0;
foreach ($reversed['format'] as $item) {
if ($counter == 2) {
break;
}
//your echo image code
++$counter;
}
My version using array_pop:
$content = file_get_contents('URL');
$json = json_decode($content, true);
// take last element of array, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// take last element of array again, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);
// Beware - using `$json['format']` later means that
// you use array without two last elements

php for each in while loop

I am trying to get specific data from a while loop and loop it x number of times.
I'm selecting this data:
$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'");
while ($adData = mysql_fetch_array($r, MYSQL_NUM))
{
$data = $adData;
$ac0 = $data['ac0'];
$ac1 = $data['ac0'];
print $ac0;
print $ac1;
}
This doesn't work. Nothing gets printed out.
What I want to do is to get ac6 to ac0 value for that specific advertisement (where token).
How can I do that?
Change your numeric fetch to an associative one, then add a foreach loop to process the result.
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
while ($adData = mysql_fetch_assoc($r))
{
foreach ($adData as $key => $value)
{
$nubmer = (int)substr($key, 2);
print $value; // or whatever you actually want to do
}
}
Also I hope you're validating $_GET['token'] against possible mischief in your code.
You can create an arrays to add the values from the result query
1st is to create an array:
$advert_AC0 = array();
$advert_AC1 = array();
$advert_AC2 = array();
$advert_AC3 = array();
$advert_AC4 = array();
$advert_AC5 = array();
$advert_AC6 = array();
Now, to add content to array
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result
while ($adData = mysql_fetch_assoc($r))
{
array_push($advert_AC0, $dData['ac0']);
array_push($advert_AC1, $dData['ac1']);
array_push($advert_AC2, $dData['ac2']);
array_push($advert_AC3, $dData['ac3']);
array_push($advert_AC4, $dData['ac4']);
array_push($advert_AC5, $dData['ac5']);
array_push($advert_AC6, $dData['ac6']);
}
}else{
echo "NO RESULT.";
}
to call for the array values, 1 by 1
$count_array = count($advert_AC0);
$i = $count_array;
while(1 <= $i){
echo "AC0: $advert_AC0[$i]<br>";
echo "AC1: $advert_AC1[$i]<br>";
echo "AC2: $advert_AC2[$i]<br>";
echo "AC3: $advert_AC3[$i]<br>";
echo "AC4: $advert_AC4[$i]<br>";
echo "AC5: $advert_AC5[$i]<br>";
echo "AC6: $advert_AC6[$i]<br>";
$i++;
}
I don't know if my answer solved your question, please comment if not.

how to get individual element from array in php?

I have dateValues as follows,
[dateVals] = 031012,041012;
it is comma seperated values. I want to make this as array and to get individual values . As i am new to PHP , i want some one's help .
$val = array[dataVals];
for($i=0;$i<sizeof($val);$i++) {
echo "val is".$val[$i]."\n";
}
is not working
use this code
$dateVals = '031012,041012';
$pieces = explode(",", $dateVals);
for($i=0;$i<sizeof($pieces);$i++) {
echo "val is".$pieces[$i]."\n";
}
it will give you proper output.
working example http://codepad.viper-7.com/PQBiZ3
$dateVals = '031012,041012';
$dateValsArr = explode(',', $dateVals);
foreach( $dateValsArr as $date) {
}
Try this code.
Try this One
$dateVals = '031012,041012';
$date_arr[] = explode(',',$dateVals);
for($i = 0 ; $i < count($date_arr) ; $i++)
{
print $date_arr[$i].'<br />';
}

Categories