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.
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 have an array of associative arrays whose names (this is one of the keys of the assoc array) are given below:
{'Red', 'Blue', 'Green'}
Now I have another larger array with names as one of the keys. Like
{'id'=>'23fe54','names'=>'Red','value'=>'3'},{'id'=>'90ks21','names'=>'Red','value'=>'4'},{'id'=>'44cb12','names'=>'Blue','value'=>'1'};
According to this I want to update the smaller (the first one) array.
The names key of the larger array tells us which assoc array of the smaller array needs to be updated. I want to then add the value to one of the fields of the smaller array.
The question is how do I select the shorter array using the condition: whether these two fields match. How do I make sure only that one gets updated?
EDIT: Expected output:
{'names'=>'Red', 'value'=>'7'},{'names'=>'Blue','value'=>'1'};
I would do this :
<?php
$names = array('Red', 'Blue', 'Green');
$values = array(
array('id'=>'23fe54','names'=>'Red','value'=>'3'),
array('id'=>'90ks21','names'=>'Red','value'=>'4'),
array('id'=>'44cb12','names'=>'Blue','value'=>'1')
);
// prepare the result array
$results = array();
foreach($names as $name) {
$results[$name] = array('names' => $name, 'value' => 0);
}
// compute values
foreach($values as $value) {
$results[$value['names']]['value'] += $value['value'];
}
// keep only values
$results = array_values($results);
// print "jsonified" result
echo(json_encode($results));
?>
I have two arrays, there is one element which is 'name' common in first and second array. Now, I want to retrieved values from second array if first array value match to second one.
code for first array:
$rs = array();
foreach ( $ex_array as $data ) {
$rs[] = array( 'name' => $data['name'] );
}
Second Array:
$entries_data = array();
foreach ( $array as $entry ) {
$name = $entry['name']['value'];
$email = $entry['email']['value'];
$entries_data[] = array(
'name' => $name,
'email' => $email
);
}
Problem is, there is only multiple names in first array, and then i have to compare first array names with the second one array, if there is match then whole data is retrieved from second array for specific name. I am trying to do this by using in_array function for search names in second array but can't fetch whole values. Any suggestions or help would be grateful for me.
is_array() is used for 1d arrays which isnt ur case use this function taken from the php documentation comments and edited by me to work for ur example
function in_multiarray($elem, $array)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom]['name'] == $elem)
return true;
else
if(is_array($array[$bottom]['name']))
if(in_multiarray($elem, ($array[$bottom]['name'])))
return true;
$bottom++;
}
return false;
}
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'];
}
//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