Laravel 5 adding an element in an array does not work - php

I am getting an array from table questions
$questions = Category::where('slug', $slug)->first()->questions->toArray();
then using foreach I iterate over array and push an array element during each iteration like below
foreach ($questions as $question) {
$question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
}
Ideally I should get response like below
array (size=5)
0 =>
array (size=6)
'id' => int 1
'category_id' => int 1
'questions' => string 'The ozone layer restricts' (length=25)
'answer_id' => int 4
'image_path' => string '' (length=0)
'options' =>
array (size=4)
0 =>
array (size=3)
...
1 =>
array (size=3)
...
2 =>
array (size=3)
...
3 =>
array (size=3)
...
1 =>
array (size=6)
'id' => int 2
'category_id' => int 1
'questions' => string 'Ecology deals with' (length=18)
'answer_id' => int 10
'image_path' => string '' (length=0)
'options' =>
array (size=4)
0 =>
array (size=3)
...
1 =>
array (size=3)
...
2 =>
array (size=3)
...
3 =>
array (size=3)
...
but Actually I am not getting options key into my questions array

The issue here is when you do a foreach, you are referring to the array by value - that is, under the hood PHP will create a copy of the variable inside the array. What you need is to access each element in the foreach by reference (note the & next to $q)
foreach ($questions as & $q) {
$q['options'] = Option::where('question_id', '=', $q['id'])->get()->toArray();
}
See:
Passing by references and the PHP docs on foreach.
Note: This is not really a Laravel issue, just PHP.

Try this (& in foreach):
foreach ($questions as & $question) {
$question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
}

You can try:
foreach ($questions as $key=>$question) {
$questions[$key]['options'] = Option::where('question_id',$question['id'])->get()->toArray();
}

Related

Show duplicate value in array only one but show all others

can i showing only one value in foreach array having multiple same value, without grouping the array firstly in the query like this :
0 =>
array (size=10)
'id' => string '1' (length=1)
'questionname' => string 'question 01' (length=36)
'answerspossible' =>
array (size=3)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
2 =>
array (size=2)
...
'answer' => string 'YES' (length=3)
'answer2' => string '' (length=0)
1 =>
array (size=10)
'id' => string '1' (length=1)
'questionname' => string 'question 01' (length=36)
'answerspossible' =>
array (size=3)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
2 =>
array (size=2)
...
'answer' => string 'YES' (length=3)
'answer2' => string 'test answer' (length=0)
Result i want in the view is to group by the questioname inside the foreach :
question 01 :
- answer & answer 2
- answer & answer 2
My code is :
foreach ($Questions as $Key => $Question) {
echo $question['questionname'];
echo $Question['answer']." & ".$Question['answer2'];
}
thnx for help :)
$justblank = ''; // just a blank variable we will use it later.
foreach ($Questions as $Key => $Question) {
echo $question['questionname'];
$questionanswers = $Question['answer']." & ".$Question['answer2'];
if($justblank == $questionanswers){
break;
}else{
echo $questionanswers;
}
$justblank .= $questionanswers;
}
Hi Mohammed, I hope this help you :).
a blank var work
$justblank = -1;
foreach ($Questions as $Key => $Question) {
if($Question['id']!=$justblank){
echo $Question['questionname'];
$justblank=$Question['id'];
}
....
}

Convert array index to custom value?

I have an array $indexedarray
printr($indexedarray) gives something like this
array (size=3)
0 => string 'Homes' (length=5)
1 => string 'Apartments' (length=10)
2 => string 'Villas' (length=6)
I want to change this arrays index also same as value, like
array (size=3)
'Homes' => string 'Homes' (length=5)
'Apartments' => string 'Apartments' (length=10)
'Villas' => string 'Villas' (length=6)
is it posssible??
You can use array_combine:
$indexedarray= ['Homes', 'Apartments', 'Villas'];
print_r(array_combine($indexedarray, $indexedarray));
Gives:
Array
(
[Homes] => Homes
[Apartments] => Apartments
[Villas] => Villas
)
But be aware that your duplicate values will be dropped. Keys will be unique!
Try This :
$myArray = [
0 => 'Homes',
1 => 'Apartments',
2 => 'Villas' ];
$newArray = [];
foreach($myArray as $key => $value){
$newArray[$value] = $value;
}
var_dump($newArray);

php Get all values from multidimensional associative array

how can i get all values from multidimensional associative array
I dont want to use print_r want to control my array put all the value in normal array with unique values
my array is look like this
array (size=10)
0 =>
array (size=3)
0 =>
array (size=1)
'Campaign' => string 'DEMO' (length=4)
1 =>
array (size=1)
'Campaign' => string 'Home_Sec' (length=8)
2 =>
array (size=1)
'Campaign' => string '' (length=0)
1 =>
array (size=0)
empty
2 =>
array (size=0)
empty
3 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'Back_Brace' (length=10)
4 =>
array (size=2)
0 =>
array (size=1)
'Campaign' => string 'Home_Sec' (length=8)
1 =>
array (size=1)
'Campaign' => string '' (length=0)
5 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'home_Sec_2' (length=10)
6 =>
array (size=1)
0 =>
array (size=1)
'Campaign' => string 'Burial_Ins' (length=10)
7 =>
array (size=0)
empty
8 =>
array (size=0)
empty
9 =>
array (size=0)
empty
I dont want to use print_r want to control my array put all the value in normal array with unique values
array_walk is an option, but here's another option if you want to try something a bit more coded by yourself, solving this problem recursively
This will flatten any n-max level array into a single array that contains all the values of all the sub arrays (including the initial array itself)
<?php
$array = array(
1 => array(1, 2, 3, 4 => array(
1, 2, 3, 4
)),
4, 5);
function recurse_values($array) {
if (is_array($array)) {
$output_array = array();
foreach ($array as $key=>$val) {
$primitive_output = recurse_values($val);
if (is_array($primitive_output)) {
$output_array = array_merge($output_array, $primitive_output);
}
else {
array_push($output_array, $primitive_output);
}
}
return $output_array;
}
else {
return $array;
}
}
print_r(recurse_values($array));
?>
If you need unique values, at the end you can add a array_unique to do this.
You can use array_walk
$array = array(...); //your values here
function output($item, $key) {
echo $key . ' =>' . $item;
}
array_walk($array, 'output');
Are you asking how you can "flatten" this multi-dimensional array into a one dimension? Possible solutions to similar problems... How to Flatten a Multidimensional Array?

PHP - retrieve data from an array

i have the following array i obtain after running a var_dump($response).
array (size=2)
'count' => int 3
'data' =>
array (size=3)
0 => array (size=38)
'ref' => string '24750.0.2530' (length=12)
1 => array (size=38)
'ref' => string '24450.0.2530' (length=12)
i would like to display the 'ref' from the above array.tried running a foreach as below but i get a notice
Trying to get property of non-object
foreach($response as $object)
{
var_dump($object->ref);
}
foreach ($response['data'] as $data) {
var_dump($data['ref']);
}
That's because it isn't an object. It is an array of arrays. Try:
foreach ($response['data'] as $data) {
var_dump($data['ref']);
}

count from several multidimensional arrays

i have foreach, which generate following arrays:
==== array 1 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'daa' (length=3)
2 =>
array
'tag' => string 'daf' (length=3)
3 =>
array
'tag' => string 'daaa' (length=4)
4 =>
array
'tag' => string 'daf' (length=3)
5 =>
array
'tag' => string 'daa' (length=3)
6 =>
array
'tag' => string 'daf' (length=3)
7 =>
array
'tag' => string 'daf' (length=3)
8 =>
array
'tag' => string 'daf' (length=3)
9 =>
array
'tag' => string 'abd' (length=3)
10 =>
array
'tag' => string 'abdaa' (length=5)
11 =>
array
'tag' => string 'abda' (length=4)
==== array 2 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'test1' (length=5)
As output i want to get something like:
array
'daf' => '7'
'daa' => '2'
'daaa' => '1'
'abd' => '1'
'abdaa' => '1'
'abda' => '1'
'test1' => '1'
The value of the new array is the count of the element from all aray generatet from the loop. array_count_values() doesn't work here...any suggestions, how to solve the problem?
Did not notice it was 2 dimensional array.
Here is another code.
var_export(
array_count_values(
call_user_func_array('array_merge', array_merge($array1, $array2))
)
);
Something a bit like this should work:
$result = array();
foreach (array_merge($array1, $array2) as $item) {
$name = $item['tag'];
if (!isset($result[$name])) {
$result[$name] = 0;
}
$result[$name]++;
}
Let's make some use of the Standard PHP Library (SPL).
You can "flatten" an array with an RecursiveArrayIterator and RecursiveIteratorIterator. As a result you get an iterator that visits each leaf of your n-dimensional array and still let's you access the actual key of the element. In the next step concat both RecursiveIteratorIterators with an AppendIterator acting like a single interator that visits each element in all of its inner (appended) iterators.
$ai = new AppendIterator;
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)));
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array2)));
$counters = array();
foreach($ai as $key=>$value) {
if ( 'tag'===$key ) {
// # because I don't care whether this array element exists beforehand or not.
// $value has to be something that can be used as an array key (strings in this case)
#$counters[$value] += 1;
}
}
If you want you can even use a FilterIterator instead of the if('tag'===$key). But imho this doesn't increase the readability/value of the code ;-)

Categories