Looping through Associative Array not working as expected? - php

I am having a array like so and I am looping trough it like this:
$options = array();
$options[0] = 'test1';
$options[1] = 'test2';
$options[2] = 'test3';
foreach($options as $x)
{
echo "Value=" . $x ;
echo "<br>";
}
It outputs as expected:
Value=test
Value=test2
Value=test3
Now I want to add some options to my array and loop trough them:
$options = array();
$options['first_option'] = 'test';
$options['second_option'] = get_option('second_option');
$options['third_option'] = get_option('third_option');
foreach($options as $x)
{
echo "Value=" . $x ;
echo "<br>";
}
But it does not work as I want. Because it outputs:
Value=first_option
Value=second_option
Value=third_option
So now I do not know how to access stored values using foreach from these guys?
Something like:
Value=first_option='test'
So when I use print_r($options)
Output is:
Array
(
[first_options] => test
[second_option] =>
[third_option] =>
)
1

your loop should look like this:
foreach($options as $key => $val){
echo "Val: ".$val;
echo "<br/>";
}

Your code is working just as expected and producing the desired result. You must have something else changing the values in $options. Correction: now that I see your edit, your functions are not returning any values, so options 1 and 2 are blank. Make sure that function returns something. Other than that, all of this code is good.
By the way, I recommend this:
$options = [
'first_option' => 'test',
'second_option' => get_option('second_option'),
'third_option' => get_option('third_option')
];
foreach($options as $key) {
echo "Value = {$key}<br>";
}
you can also use:
foreach($options as $key => $value) {
echo "Value - {$value} = {$key}<br>";
}
or you could at least replace array() with just []. Those are just some suggestions for neatness.

Related

How can I get keys of a name attribute

I have this name="opt['.$id.']" value="'.$points.'" inside a checkbox input.Does anybody knows how I can get the $id?
UPDATED:
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
$gift_ids2 = implode(", ", $gift_ids);
}
echo $gift_ids2;
}
But I don't get any value on echo..
You need to iterate over the HTML array. Something like this should do it for you:
foreach($_POST['opt'] as $id => $value) {
Demo: https://eval.in/585379
your used array so you need to Iterate the $_POST['opt'] value
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
foreach($_POST['opt'] as $id => $value)
{
echo $id //key example 1
echo $value //value example 100
}
If your $_POST is like this
$_POST = array('opt' => array('1'=>100 ), 'eksasrgirwsh' => 'other');
and you are giving $_POST['opt'] to foreach then your array for foreach is
$_POST['opt'] = array('1'=>100);
then you can't use implode in foreach because it give you an error. Do it without implode.
foreach($_POST['opt'] as $id => $value) {
$gift_ids = $value;
echo $gift_ids;
}

How to get the value of specific object in PHP

I have a result array which looks like this:
Array
(
[formdata] => [{"id":"1"},{"name":"name"}]
)
Now I want to get the value of id but I can't get it right.
The code I've done so far is:
foreach ($text as $key => $file) {
print_r($file['id']); //<--- it shoud print 1
}
$var2 = json_decode($var['formdata'], true);
echo $var2[0]['id'];
Simple Example to what Babak commented:
$var['formdata'] = '[{"id":"1"},{"name":"name"}]';
$var2 = json_decode($var['formdata']);
foreach($var2 as $item) {
echo $item->id;
}

How to store each array value in a variable with PHP

I have an array that looks something like this:
Array
(
[2] => http://www.marleenvanlook.be/admin.php
[4] => http://www.marleenvanlook.be/checklogin.php
[5] => http://www.marleenvanlook.be/checkupload.php
[6] => http://www.marleenvanlook.be/contact.php
)
What I want to do is store each value from this array to a variable (using PHP). So for example:
$something1 = "http://www.marleenvanlook.be/admin.php";
$something2 = "http://www.marleenvanlook.be/checklogin.php";
...
You can use extract():
$data = array(
'something1',
'something2',
'something3',
);
extract($data, EXTR_PREFIX_ALL, 'var');
echo $var0; //Output something1
More info on http://br2.php.net/manual/en/function.extract.php
Well.. you could do something like this?
$myArray = array("http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
$i = 0;
foreach($myArray as $value){
${'something'.$i} = $value;
$i++;
}
echo $something0; //http://www.marleenvanlook.be/admin.php
This would dynamically create variables with names like $something0, $something1, etc holding a value of the array assigned in the foreach.
If you want the keys to be involved you can also do this:
$myArray = array(1 => "http://www.marleenvanlook.be/admin.php","http://www.marleenvanlook.be/checklogin.php","etc");
foreach($myArray as $key => $value){
${'something'.$key} = $value;
}
echo $something1; //http://www.marleenvanlook.be/admin.php
PHP has something called variable variables which lets you name a variable with the value of another variable.
$something = array(
'http://www.marleenvanlook.be/admin.php',
'http://www.marleenvanlook.be/checklogin.php',
'http://www.marleenvanlook.be/checkupload.php',
'http://www.marleenvanlook.be/contact.php',
);
foreach($something as $key => $value) {
$key = 'something' . $key;
$$key = $value;
// OR (condensed version)
// ${"something{$key}"} = $value;
}
echo $something2;
// http://www.marleenvanlook.be/checkupload.php
But the question is why would you want to do this? Arrays are meant to be accessed by keys, so you can just do:
echo $something[2];
// http://www.marleenvanlook.be/checkupload.php
What I would do is:
$something1 = $the_array[2];
$something2 = $the_array[4];

array result using foreach statement display in json in php

I am getting the result from web service SOAP client. I have created an array to get the result and display it using json format. I am getting few of my results properly. I have SerialEquipment parameter which is array and i need to get the result using foreach loop. I am doing an mistake there. I dont know how can i assign my $vehiclResult array in this for each statement. So that all the results at last i will collect and display using json using vehicleResult array.My mistake is in the foreach loop.
structure for SerialEquipment parameters:
Code:
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$vehiclResult = array(
'WE_Number' => $vehicle['WE Number'] ."<br>",
'Vehicle Type'=> $vehicle['Vehicle Type'] . "<br>",
'HSN' => $vehicle['HSN'] . "<br>",
'TSN' => $vehicle['TSN'] . "<br>"
);
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['SerialEquipment'] = $key. "<br>";
$vehiclResult[$key]['Code'] = $obj->Code. "<br>";
$vehiclResult[$key]['Desc Short'] = $obj->Desc_Short. "<br>";
$vehiclResult[$key]['Desc Long'] = $obj->Desc_Long. "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc). "<br>";
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc). "<br>";
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
}
You need to check if your array have the key so:
if(!isset($vehiclResult[$key]))
if not, you need to create it:
$vehiclResult[$key] = array(); // as an array
Also, you don't really need to make a description of your "item". You can Parse your JSON on the result page to output some text.
You can do something like.
Do something like:
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['serial'] = $key;
$vehiclResult[$key]['code'] = $obj->Code;
$vehiclResult[$key]['short_desc'] = $obj->Desc_Short;
$vehiclResult[$key]['long_desc'] = $obj->Desc_Long;
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2;
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode;
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc;
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode;
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc);
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode;
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc);
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
If you would keep your "text" and your <br> code, do the samething but add what you want to output after the "="
EDIT
** A HAVE CHANGE THE CODE PREVIOUSLY..
if you want to test your $vehiclResult, try something like:
foreach($vehiclResult as $key=>$value){
if(!is_array($value))
var_dump($value);
else {
foreach($value as $key2=>$value2){
if(!is_array($value2))
var_dump($value2);
else {
foreach($value2 as $key3=>$value3){
var_dump($value3);
}
}
}
}

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Categories