This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 8 months ago.
I want to create an array of associative arrays in a while loop. In each iteration of the while loop I want to add a new element in the array. How I can do that? After that I want to pass this array in a foreach and print the data. I have this part of code for now but obviously something is wrong with that.
while($row2 = mysql_fetch_array($result))
{
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2['text']);
}
To add an element in the end of an array use []
Example:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
Obviously, okay, first pick it apart so there's something to learn:
while($row2 = mysql_fetch_array($result))
{
...
}
This part look's okay, let's look inside the loop:
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
There are multiple points. Probably most important is, as that is inside a loop, you overwrite $myarray in each iteration. You want to add to an array instead. Let's do this:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
$myarray[] = $row2; # add the row
}
After that you can output it to proof that it basically works:
var_dump($myarray);
That shows you an array that contains all rows. You then only need to change your database query so that it only returns the fields you're interested in.
In case you can't do that with the database, you can manipulate the array as well:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
$myarray[] = array(
"id" => $theid,
"name" => name($id),
"text" => $row2['text']
);
}
var_dump($myarray);
Now the result should look like you want it. To output $myarray:
foreach ($myarray as $number => $row)
{
echo '<div>Number ', $number, ':<dl>';
foreach ($row as $k => $v)
{
printf("<dt>%s</dt><dd>%s</dd>\n", $k, htmlspecialchars($v));
}
echo '</dl></div>'
}
If you're trying to add to $myarray in each iteration, do it like this:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
or like this:
array_push($myarray, array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]));
Obviously your access to $row2 looked wrong, so I assumed that here to be right
$myarray = array();
while($row2 = mysql_fetch_array($result)) {
// append something to your array with square brackets []
$myarray[] = array("id"=> $row2['id'], "name" => $row2['name'], "text"=>$row2['text']);
// or to maker this even shorter you could do
$myarray[] = $row2; // ... because it has the same array key names
}
Then later when you want to read from it:
foreach($myarray as $val) {
echo $val['name'].' (ID: '.$val['id'].') wrote following text: '.$val['text'];
}
Related
I have JSON that shows multiple key-value pairs. I'd like to loop through and create a new array with only the key-value pairs I want in order to display them. This is my attempt, but of course, my code is re-writing my array ($new_array) to have only one element.
//SAMPLE JSON
[{"PropertyId":"555","FloorplanId":"555","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"},{"PropertyId":"666","FloorplanId":"666","FloorplanName":"Studio","Beds":"0","Baths":"1.00","AvailabilityURL","UnitTypeMapping":".058500"}]
//GET ALL JSON FROM URL
$json = file_get_contents('<URL>');
$data = json_decode($json);
// print_r($data); //ALL keys
//GET JUST THE KEYS I WANT
$new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");
// Create new array
foreach($data as $item) {
$new_array['FloorplanName'] = $item->{'FloorplanName'};
$new_array['Beds'] = $item->{'Beds'};
$new_array['Baths'] = $item->{'Baths'};
}
//loop over $new_array
foreach($new_array as $item) {
$item->{'FloorplanName'};
$item->{'Beds'};
$item->{'Baths'};
}
Right now, you set associative keys on $new_array and overwrite your data each time through your foreach loop. Instead, you need to add an item (a sub-array) to $new_array and assign the data to the sub-array.
Instead of this:
//GET JUST THE KEYS I WANT
$new_array = array("FloorplanName"=>"","Beds"=>"","Baths"=>"");
// access property of object in array
foreach($data as $item) {
$new_array['FloorplanName'] = $item->{'FloorplanName'};
$new_array['Beds'] = $item->{'Beds'};
$new_array['Baths'] = $item->{'Baths'};
}
You need
$new_array = array(); // this array should be empty
// access property of object in array
foreach($data as $item) {
$new_array[] = array(
'FloorplanName' => $item->{'FloorplanName'},
'Beds' => $item->{'Beds'},
'Baths' => $item->{'Baths'},
);
}
Also, to loop through the new array, you need to change your final loop:
//loop over $new_array
foreach($new_array as $item) {
echo $item['FloorplanName'];
echo $item['Beds'];
echo $item['Baths'];
}
I am trying to get the multidimensional array values from an array using a foreach loop. But it just says undefined index name
while($row = mysqli_fetch_assoc($qry)) {
$main[]['id'] = $row['categories_id'];
$main[]['name'] = $row['categories_name'];
}
foreach($main as $m) {
$main_filters .= '<li>'.$m['name'].'</li>';
}
so sure what I am doing wrong here, any ideas, i.e. how do I get the multidimensional values of all the elements in the array array $main, id and name?
Replace
$main[]['id'] = $row['categories_id'];
$main[]['name'] = $row['categories_name'];
with
$main[] = [
'id' => $row['categories_id'],
'name' => $row['categories_name']
];
otherwise you create two new element in each iteration, and you don't want that.
I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');
Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}
//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
Before for loop:
$data = array();
Then in your loop:
$data[] = array($catagory => $question);
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question