I’m not sure about the logic of having the foreach in the for loop.
The foreach is iterating through a sub-array, so $value is not an array, but an individual value of the sub-array, which are all either strings or numbers, though it never gets past the initial string.
I can only guess at your intention, but I think you only want a foreach, not a nested loop.
This looks a bit like a home-made foreach to me.
Though I’m not sure of the application or data source, but it looks like using objects here (or array of objects), instead of nested arrays may be a better option.
A. You need to fetch the data as an associate array only, so that you are not doubling the amount of data. You are currently fetching the data as both an associative and a numerical array.
B. What result are you trying to produce? I appears you are just trying to get the chassis_name values, probably for some heading display? If so, just use array_column().
I have an array of assets, I want to loop through it and print out each, while separating by type (so those with a chassis name go in a different area than those with a server name).
like if I get
Well that error code is telling you just that. You’re passing in a string, the 2nd parameter is supposed to be an array. What do you think you should really be giving it then?
I wouldn’t necessarily use for loops for something like this. I’d use 2 foreach loops to access both arrays and then do the condition and use a break to break out of the loops.
Ignoring why you have this mix of data, instead of just querying for the data you want, I would use php array functions to filter the data -
<?php
// sample data
$assetArray[] = ['chassis_name'=>'jyrkyui','chassis_id'=>1,'beginning_ru'=>29.0,'ending_ru'=>45.0];
$assetArray[] = ['chassis_name'=>'eghudjgey','chassis_id'=>2,'beginning_ru'=>14.0,'ending_ru'=>27.0];
$assetArray[] = ['server_name'=>'hfjk','server_id'=>1,'beginning_ru'=>11.0,'ending_ru'=>12.0];
// define a search term
$search = ['key'=>'chassis_name', 'value'=>true];
// use array_filter() with a call-back function to keep only the data matching the search term
$result = array_filter(
$assetArray,
function ($arr) use ($search) {
return isset($arr[$search['key']]) && $arr[$search['key']] == $search['value'];
}
);
// examine the result data
echo '<pre>'; print_r($result); echo '</pre>';
// loop over $result to use the filtered data
foreach($result as $row)
{
// use elements in $row here...
}