Getting the name of an array dynamically - php

I have an array which looks like this:
$example = [
['rendered'][0]['rendereditem1']
['rendered'][4]['rendereditem2 and more']
['rendered'][2]['rendereditem3']
]
Now I want to iterate with foreach to get the contents of 0,4,2!
Normally I would write:
foreach($example as $value){
print $value['rendered'][int which is the same everywhere];
}
But that is obviously not working because the array name is always different...how could I iterate in this case?

Simply add a second loop to iterate over the members :
foreach($example as $value) {
foreach($value['rendered'] as $key=>$item) {
// Do what you want here, $key is 0,4,2 in your example
}
}

Related

Displaying data from a CSV file with multi-dimensional PHP array

I'm trying to pull data from a CSV file that contains vehicle make, model, mileage etc...
Using this example from php -
<?php
$csv = array_map('str_getcsv', file('csv/csvin.csv'));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<div id='car'>".$key.":".$value."</div></br>";
}
}
?>
This is the array I get -
BodyStyle:"Station Wagon"
"DaysInStock":"27"
"Make":"Toyota"
"Model":"Prius v"
"MSRP":"0"
"SellingPrice":"26995"
"StockNumber":"387515"
"Trim":"Three"
"VIN":"JTDZN3EU9E3306528"
"Year" :"2014"
Now when I attempt to manipulate it or pull any individual values I simply cannot. How would I go about displaying this information with HTML tags for each value?
I have tried this:
print_r ($csv[0]['Make'];
echo $csv[0]['Make'];
Just to try and display a value but still nothing. I noticed for some reason the "BodyStyle" doesn't contain quotes like the rest so something definitely seems fishy.
From here how would I strip the quotes and break out each value?
This is the error being thrown -
Invalid argument supplied for foreach() in
Thanks in advance!
foreach($csv as $car){
echo "<tr><td>Make:</td><td>".$car['Make']."</td></tr>";
}
alternatively:
foreach($csv as $car){
foreach($car as $key=>$value){
echo "<tr><td>".$key."</td><td>".$value."</td></tr>";
}
}
alternatively:
echo $csv[0]['Make'];
Try this one :
print_r ($csv[0]['Make']);
Basically the $csv variable is an array, to get its values you have to use the loop function, something like :
foreach ($csv as $data) {
foreach ($data as $index => $value) {
if ($index == "make") {
echo $value;
}
}
}
If you notice it a bit, the outer array is called indexed array (array with indexes) and to traverse the values use foreach ($csv as $data), while the inner array is called associative array (this array does not use number as index, but a name), and to traverse it use foreach ($data as $index => $value).
Try it and you'll see :)
PS: Sorry I didn't notice the inner array, for this case Richard's answer is the correct one. I have added a credit to his answer for giving a correct answer.
So I figured out that I only need 1 foreach loop like so -
foreach($csv as $car){
$type = $car[0];
$echo $type;
}
Works now and thanks all for the help!

json_encode get values foreach object

Hello I can't figure out how to loop through this json encoded array and for each object, get all its values. I need each value as a variable for itself.
echo json_encode($formulars);
This is what i get when i echo it out
[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}]
I have tried this piece of code and I managed to get out the project_name from the first object and that's it:
foreach ($formulars as $current => $project_name) {
$project_name['project_name'];
}
So is there any way i can get all the variables for each object in my array instead of just the project_name?
Like this:
foreach ($formulars as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
Thanks in advance
Seems like you have an objects inside an array. So you will need to loop through the array and get each object. Just JSON_DECODE your encoded string like below.
Perhaps:
$data = json_decode($formulars,true);
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/
//You should now be able to do this
foreach ($data as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
The reason I loop is because there is a object inside an array(Javascript way I think).
Use json_decode to convert the json object to an array; then use foreach to loop through the array. That should work.
<?php
$arr_json = json_decode($formulars);
foreach($arr_json as $key => $value)
//Code to perform required actions
?>
This should give you some ideas.
Use json_decode (with TRUE for getting an associative array)to convert your JSON object to an associative array. After that, you can use a foreach loop to traverse through your multidimensional array and print the required values.
Code:
$json = json_decode($string, true);
foreach ($json as $key => $value) {
foreach($value as $key2 => $value2) {
echo $value2."\n";
}
}
Working Demo!

PHP - looping through an array of JSON Variables

I have the following array that is in PHP (this is a print_r() output).
I'm currently struggling to loop through this data - need to be able to process each part and access the values in each array item. How can I do this.
I've tried the following unsuccessfully...
foreach (array as $key => $value) {
echo $key;
}
Try this. Since you have an array of objects, you should be able to access each object property using ->
foreach($array as $value) {
echo $value -> userid;
}
It should echo out all the user id in that array of objects
You have an array of objects, so try something like this:
<?php
foreach ($array as $value) {
echo $value->userid;
echo $value->action;
echo $value->photo_name;
}
You don't need the $key since you're not using it in the loop. Each iteration will put the object in the $value variable, on which you can access it's properties.

PHP foreach of multidimensional array

I have an array and it has two arrays inside of it...I am able to access what I want for the first row by doing this...
print_r( $_SESSION['shopcart']['cart']['qty']);
How would I write that in a foreach?
Thanks,
J
foreach($_SESSION['shopcart']['cart']['qty'] as $value) {
echo $value;
}
you would do something like this:
to dump the array: $_SESSION['shopcart']['cart']
foreach($_SESSION['shopcart']['cart'] as $key=>$value){
echo $key." => ".$value."<br/>";
}
If you want to iterate through multiple dimensions, you can nest foreach as follows:
foreach($_SESSION['shopcart'] as $cart) {
foreach ($cart as $qty) {
// do something
}
}
Though I'd need a little more information about the array structure and what you really want to do in order to provide usable code, this is probably in the right ballpark.
I would recommend you you do do like this:
foreach($_SESSION['shopcart'] as $key=>$value){
if(is_array( $value ) ){
foreach($value => k1 => $v1){
//do something here if array
echo $k1." => ".$v1."<br/>";
}
}else{
//do something here if not array
}
}

how to add another attribute using foreach loop to an array of rows

I am using a foreach loop on an array of rows in a model file in CodeIgniter.
What i want to do is reflect the changes i make in every row ,in the foreach loop ,to the original array.
$unique = $this->db->get_where('list', array('item_index' => $item));
foreach ($unique->result_array() as $row)
{
$row["status"]= "Not Unique";
if($row["bid_amount"]==$amount)
{
if($count==0){ $row["status"]="Unique and Final"; }
else {$row["status"]="Unique but Not Final"; }
}
$count++;
}
return $unique;
I am adding another attribute to each row here and i want to echo this attribute corresponding to each row in a view file.
But i am getting error Undefined index: status.
How can i possibly reflect the changes in the array to be returned.
Assign the result_array() to a variable, iterate over it, but change the original array and not the local one. PHP's foreach comes in two flavours:
foreach($arr as $value) and foreach($arr as $key => $value)
Try this:
$results = $unique->result_array();
foreach ($results as $rK => $rV){
$results[$rK]["status"]= "Not Unique";
//other stuff.
}
return $results;
Alternatively, you can pass by reference:
foreach ($results as &$result) {
$result['status'] = "Not Unique";
}
See the PHP docs on arrays. Specifically Example 10.
In your foreach the $row refers to a variable that's local to the loop. Thus changing it does not affect the data in $unique.

Categories