//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
Related
I'm trying to create an unknown number of arrays dynamically inside a foreach loop, merge them all at the end into one array, and use this in a JSON format for Google Analytics.
So far I have the following code which is throwing an error at the merge part:
$p=1;
foreach(...){
...
$arr = 'arr'.$p;
$name = $order->ProductGroupName;
$name = str_replace("'", "", $name);
$arr = array(
"name"=>$name,
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
for ($q = 1; $q<$p; $q++){
$arry = 'arr'.$q;
$merge = array_merge($arry, $merge);
};
How do I create the arrays dynamically and merge them at the end, please?
I'm relatively new to PHP and have tried my best to get this to work.
I think I understand what you're trying to do. Just dynamically append [] to the array and you don't need to merge:
foreach($something as $order) {
$arr[] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
}
If you want to have string keys for whatever reason, then:
$p = 1;
foreach($something as $order) {
$arr["SomeText$p"] = array (
"name"=>str_replace("'", "", $order->ProductGroupName),
"id"=>$order->ProductCode,
"price"=>$order->RRP,
"quantity"=>$order->Quantity
);
$p++;
}
And that's it. Check with:
print_r($arr);
Things like $arry = 'arr'.$q; stink of variable variables (though not done correctly) and shouldn't be used.
Here is my code
$temp = $this->whereBetween('id', [$sid,$eid])
->select('id','temperature')
->get();
will return
[{"id":1,"temperature":34.5},{"id":2,"temperature":32.56},
how do i get only result like this, remove the key and pass the value only.
[{1,34.5},{2,32.56}]
I have using lists but it only return partial or all field.
You need to rebuild the array. I've tested this code and it works:
$array = [];
foreach($temp as $k => $v) {
$array[] = [$v['id'], $v['temperature']];
}
After that just serialize this array or use as is.
The function that you search, is array_values.
Iterate over your array, use that function, and save it back to an array.
For example:
$newArray = array();
foreach ($temp as $row) {
$newArray[] = array_values($row);
}
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'];
}
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'];
}
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
}
}
}