How do I access each value in array? [duplicate] - php

This question already has answers here:
how to extract a column from mysql result set?
(2 answers)
Closed 5 months ago.
I have attempted numerous times trying access each value in a array. The array contains the database results retrieved from the select query.
$query = DB::getInstance()->query("SELECT orderStatus FROM customerOrders");
foreach ($query->results() as $orderered) {
$result_array = array($orderered);
//print_r($result_array);
$orderData = array_map(function ($object) { return $object->orderStatus; }, $result_array);
$test = json_decode(json_encode($result_array), true);
$ORvalue = serialize($test);
$ORvalue2 = unserialize($ORvalue);
$orderValueNEW = call_user_func_array('array_merge', $ORvalue2);
print_r($orderValueNEW);//debug
}//close foreach loop
Result it prints are:
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 1 )
Array ( [orderStatus] => 1 )

What you're doing should work to retrieve each row, but if you want to access the orderStatus value, you can do this with your result array:
foreach ($result_array as $resultRow) {
echo $resultRow['orderStatus'];
}
That should work, if that's what you mean. If you want to access the orderStatus value in the first loop, you can refer to it as $row['orderStatus']. Or, if you do a SELECT * in your query and you want to go through all values from the query, you can just make another loop like foreach ($row as $column => value) { ... }

Are you looking to just print the values and not the associate key/value pairs?
Changing
$result_array[] = $row;
to
$result_array[] = $row['orderStatus'];
should do the trick.

Related

Loop not working with assosiative array Php

Can i make multidimensionalarrry to assosiative array, Right now i am getting following result
Array
(
[0] => Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
[1] => Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
}
)
I just want to put all values in single, i want result like following array
Array
(
[id] => 1
[minimum_marks] => 55
[maximum_marks] => 65
)
Array
(
[id] => 2
[minimum_marks] => 44
[maximum_marks] => 70
)
Here is my code,My code not showing only one record with loop (code should showing all minimum_marks and maximum_marks), where i am wrong ?
$result = $query->result_array();
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
}
print_R($simpleArray);
I don't know why are you expecting this output. But my suggestion, if you want it really?
$simpleArray = [];
foreach ($result as $skuArray) {
$simpleArray['minimum_marks'] = $skuArray['minimum_marks'];
$simpleArray['maximum_marks'] = $skuArray['maximum_marks'];
print_R($simpleArray);
}
Print the value inside loop, so it wont push and it wont create multiple array. every time, it will overwrite. But please be sure, finally you get last array value only on the simpleArray. Hope you understood!
Let me explain with example. If you want to display the marks in table, I will suggest you to return directly like below instead of creating variable and retrieving it again.
echo '<table>
<tr><th>Min Marks</th><th>Max Marks</th></tr>';
foreach ($result as $skuArray) {
$minMarks = $skuArray['minimum_marks'];
$maxMarks = $skuArray['maximum_marks'];
echo '<tr><td>'.$minMarks.'</td><td>'.$minMarks.'</td></tr>';
}
echo '</table>';
I don't really understand what you want.
If you want to get your array in two different variables you can try this:
Use dynamic variables, the name of the variable is dynamically generated in your loop.
foreach($result as $key => $_array){
//$key is your inder of you multidimensional
$name_variable = '_array_number_'.$key; //Name of the variable
$$name_variable = $_array; //Instanciate dynamic variable
}
//You got now this two array
print_r($_array_number_0);
print_r($_array_number_1);
But please be more precise next time with what you expect and why you need this.
By the way, what happened to your code is that in the first loop you instanciate 'minimum_marks' and 'maximum_marks' in $_simple_array.
But in your second loop you overwrite the value of 'minimum_marks' and 'maximum_marks'.

Convert array of values to nested associative array [duplicate]

This question already has answers here:
php create multidimensional array from flat one
(4 answers)
Closed 4 years ago.
php create multidimensional array from flat one
Tried this but counting backwards won't work as I need to move from start to finish in the order in which the array is originally.
I have a simple array:
0 => Item #1
1 => Item #2
2 => Item #3
I need to create an associative array from the above like so:
Item #1
=> Item #2
=> Item #3
Where each value becomes the key for the parent item. This must be done in a while loop not recursion. It MUST move forward, the loop performs a look-ahead for validation purposes, so the original order is imperative
Thanks
EDIT - this is giving me the intended result I just can't get my around how to do this in the main loop |
array:3 [
0 => "workorder"
1 => "company"
2 => "name"
]
$array['workorder'] = [];
$temp = &$array['workorder'];
$temp['company'] = [];
$temp2 = &$temp['company'];
$temp2['name'] = [];
dump($array);
exit;
EDIT 2 | Main loop
$type = current($types);
while (array_key_exists($type, $this->types)) {
$nextType = next($types);
// ... do stuff
$type = $nextType;
}
return $array;
Try
// This array contain the keys for associative array
$arrayKeys = ['name1', 'name2', 'name3'];
// This array contain the values for associative array
$arrayItems = ['item1', 'item2', 'item3'];
// this array will be the associative array
$newArray = [];
$count = count($arrayKeys) -1;
while( $count >= 0 ){
$newArray[ $arrayKeys[$count] ] = $arrayItems[$count];
echo '<Br>';
$count--;
}

Access subset array with foreach [duplicate]

This question already has answers here:
Looping a multidimensional array in php
(3 answers)
How to load Google Maps in wpf window?
(2 answers)
Closed 5 years ago.
i have arrays like this
Any idea how to access #items subset with foreach or somthing fast like this?
Array
(
[0] => Array
(
[#theme] => item_list
[#items] => Array
(
[0] => Array
(
[nid] => 1
[changed] => 1514034947
[title] => TITLE 1
)
[1] => Array
(
[nid] => 2
[changed] => 1514034947
[title] => TITLE 2
)
)
)
[1] => Array
(
[#theme] => pager
)
BEST
As your elements are located below 3 levels so you need to use foreach thrice like below:
foreach($data as $items_list){
foreach($items_list[#items] as $items){
foreach($items as $val){
echo $val['nid'];
}
}
}
You can simply count array everytime and add condition before foreach loop to check if further array exists or not.
Like you can count main array and add condition with while loop and then use foreach like below:
$count = 0;
while($count<count($array)){
foreach($array[$count]['#items'] as $items ){
foreach($items as $val){
echo $val['nid'];
}
}
$count = $count+1;
}
Before doing anything, its better if you debug your multiple arrays like below:
echo "<pre>"; print_r($array); die;
You can use a nested foreach to get the final item list from this array object...
foreach($data as $items_list)
{
foreach($items_list[#items] as $items)
{
// do something here....
}
}
Assuming the array structure is exactly as you posted here is something you can experiment with. I don't know what you want to do with each item so this example just prints out the elements of each one:
foreach( $array as $outerarray )
{
foreach( $outerarray['#items'] as $item )
{
echo "{$item['nid']} {$item['changed']} {$item['title']}\n";
}
}

How can I filter a multidimensional array and count the filtered values?

I have an array coming from a mysql database. So it is structured this way (just the first two entry):
Array
(
[0] => Array
(
[id_cre] => CD000000001
[0] => CD000000001
[id_az] => AZ000000001
[1] => AZ000000001
)
[1] => Array
(
[id_cre] => CD000000002
[0] => CD000000002
[id_az] =>
[1] =>
)
)
I would like to count how many entries in the array have [id_az] =>''.
If I do:
count($creds)
I get 2 (the number of items in the array).
I'd prefer to reuse this array (the query runs already for another report), instead of doing a new query with the WHERE clause to subselect WHERE id_az = ''.
Any hint(s)?
This should work for you:
Just get the column id_az with array_column() and count() the array then, e.g.
echo count(array_column($creds, "id_az"));
Why not use a good old foreach loop?
$count = 0;
foreach($data as $row)
{
$count += empty($row['id_az']) ? 0 : 1;
}
or alternativly an array_map with a anonymous function
$count = 0;
array_map(function($row) use (&$count) { $count += empty($row['id_az']) ? 0 : 1; }, $data);
But this is PHP >5.3. Callbacks won't work, since you won't have access to a variable to store your count in.

PHP in_array() not finding value [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
in_array() and multidimensional array
Got the following array returned from a database using this code:
$skus = array();
$result = mysql_query($sql);
if($result){
while($rows = mysql_fetch_array($result)){
$skus[]=$rows;
}
}
Results:
Array (
[0] => Array {
[0] => PUBELI
[group_sku] => PUBELI
)
[1] => Array (
[0] => PUBESSENTIALS
[group_sku] => PUBESSENTIALS
)
[2] => Array (
[0] => PUBMGRPROGROUPED
[group_sku] => PUBMGRPROGROUPED
)
[3] => Array (
[0] => PUB25GROUPED
[group_sku] => PUB25GROUPED
)
)
I'm looking for this value using in_array:
if (in_array('PUBESSENTIALS', $skus))
and it returns false. Am I doing this correctly?
Why would the array values not be enclosed in quotes if the values in the DB are strings?
Don't use PHP if you may do something with MySql!
Try this solution:
$sql = "SELECT * FROM table WHERE str = 'PUBESSENTIALS'"; // some query just add WHERE
$result = mysql_query($sql);
if($result) $Row = mysql_fetch_array($result)
Assuming $skus is the full array shown above, then 'PUBESSENTIALS' would not be in $skus, because $sku's contains child arrays.
However, in_array('PUBESSENTIALS', $skus[1]) would return true.
try looping through each $skus element, and then checking that child element for in_array(value, childArray)
You are only looking into the first array, and not any other array. You should look through each to test every sub-array. Something like this could do the job:
foreach($skus as $sku) {
if (in_array('PUBESSENTIALS', $sku)) {
return true;
}
}

Categories