Creating An Associative Multi Dimensional Array from loop in PHP - php

How can I create an array like the following in PHP from a database result set using a loop:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}

I think something like this should do it:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
OR, to be more specific (if your query is returning more columns than just id and name):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}

$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
$key = $result['name']{0};
if(!isset($indexArray[$key])) {
$indexArray[$key] = array();
}
array_push($indexArray[$key], $result);
}

$results = array();
while($result = $db->fetch($query)) {
$key = strtoupper($result['name'][0]);
if(!isset($results[$key]))
$results[$key] = array();
$results[$key][] = $result;
}

Related

Cannot merge nested arrays data from find('all') in cakephp2

I try to merge the data's in the arrays 'c' and 'a' inside MyData with the following code, but the outcome was still corrupted.
Are there something wrong with my code ? Or am I simple making a mistake with how I merge the arrays ? I'm doing all sorts of stuff to solve the problem but cannot find any solution that works. Some examples or tips will be great!
Want to merge [my_test] and [my_date] inside [MyData].
Array
(
[0] => Array
(
[MyData] => Array
(
[id] => 79
[my_birth_day] => 1990-06-20
[my_address] => 400
[my_age] => 26
[my_name] => Joy
[my_id] => 1
[created] => 2017-06-19 15:39:44
)
[c] => Array
(
[my_test] => math
)
[a] => Array
(
[my_date] => 2017-08-13
)
).....Loops
[1] => Array
(
I would want the result to be like
Array
(
[0] => Array
(
[MyData] => Array
(
[id] => 79
[my_birth_day] => 1990-06-20
[my_address] => 400
[my_age] => 26
[my_name] => Joy
[my_id] => 1
[created] => 2017-06-19 15:39:44
[my_test] => math
[my_date] => 2017-08-13
I made a logic to merge the arrays and display it as the above code , but wasn't able to merge
$res = $this->find( 'all', $cond); // All the data are fetchd from this $res
$count = count($res);
for($i=0;$i<$count;$i++){
$result[] = $res[$i] ;
$fixed_arrays[] = $result[$i]['MyData'];
if (!empty($result[$i]['c'])) {
$corrupt_c_array = $result[$i]['c'];
$fixed_arrays = array_merge($fixed_arrays,$corrupt_c_array);
}
if(!empty($result[$i]['a'])) {
$corrupt_a_array = $result[$i]['a'];
$fixed_arrays = array_merge($fixed_arrays, $corrupt_a_array);
}
}
$result['data'] = $fixed_arrays; // This $result['data'] should show the expected result.
[Update]
Heard about a function called set::combine for cakephp2, Is there a way to use set::combine since it's cakephp2?
You can create the temporary $data array and merge everything and then assign to the $fixed_arrays list
<?php
$res = $this->find( 'all', $cond); // All the data are fetched from this $res
$count = count($res);
for($i=0;$i<$count;$i++){
$result[] = $res[$i] ;
$data =array(); //temporary array
$data['MyData'] = $result[$i]['MyData'];
if (!empty($result[$i]['c']) && isset($result[$i]['c']['my_test'])) {
$corrupt_c_array = $result[$i]['c'];
$data['MyData']['my_test'] = $result[$i]['c']['my_test'];
}
if(!empty($result[$i]['a']) && isset($result[$i]['a']['my_date'])) {
$corrupt_a_array = $result[$i]['a'];
$data['MyData']['my_date'] = $result[$i]['a']['my_date'];
}
$fixed_arrays[] = $data;
}
$result['data'] = $fixed_arrays;
If you use the condition then you can not get the all values if it will blank so use like this :
<?php
$res = $this->find('all', $cond); // All the data are fetched from this $res
$count = count($res);
for ($i = 0; $i < $count; $i++) {
$result[] = $res[$i];
$data = array(); //temporary array
$data[$i]['MyData'] = $result[$i]['MyData'];
$data[$i]['MyData']['my_test'] = $result[$i]['c']['my_test'];
$data[$i]['MyData']['my_date'] = $result[$i]['a']['my_date'];
}
$result['data'] = $data;
Just Print the $data or $result to get array like you want.
$res = $this->find ( 'all', $cond );
foreach ( $res as &$result ) {
$result ['MyData'] ['my_test'] = $result ['c'] ['my_test'];
$result ['MyData'] ['my_date'] = $result ['a'] ['my_date'];
unset ( $result ['a'] );
unset ( $result ['c'] );
}
echo "<pre>";
print_r ( $res );
exit ();

PHP array and foreach

This is my current code:
$exceptions = array();
foreach ($rows as $row) {
$opens = $row['opens'];
$closes = $row['closes'];
$joined = array($opens, $closes);
$exception = join('-', $joined);
$exceptions[] = array (
$row['date'] => array($exception),
);
}
Which gives:
Array ( [0] => Array ( [06/09] => Array ( [0] => 01:00-22:00 ) ) [1] => Array ( [06/10] => Array ( [0] => 01:00-22:00 ) ) )
But I'm aiming for this because the plugin requires this form:
Array ( [06/09] => Array ( [0] => 01:00-22:00 ) [06/10] => Array ( [0] => 01:00-22:00 ) )
Is there a way to rearrange the array to achieve this?
// Assumptions
// 1. You have `$first_exception` within scope
// 2. You have `$rows` within scope
$exceptions = array();
foreach ($rows as $row) {
// Assumption: `$row` has key `date`
$exceptions[$row['date']] = array (
$first_exception
);
}
Try this:
$exceptions = array();
foreach ($rows as $row) {
$exceptions[$row['date']] = array ($first_exception);
}
You could try this code. And try to read about arrays http://php.net/manual/en/book.array.php
$exceptions = array();
foreach ($rows as $row) {
$exceptions[$row['date']][] = array($first_exception);
}

How to formate array

I'm trying to store data in an array from a database.
After printing the array, I need something like this :
Array ( [ABBA] => ?search=ABBA [ACDC] => ?search=ACDC [Ace of Spades] => ?search=AceOfSpades)
But currently, I have this :
Array ( [url] => ?search=ABBA [title] => ABBA ) Array ( [idtitle] => ?search=ACDC [title] => ACDC ) Array ( [idtitle] => ?search=AceOfSpades [title] => Ace of Spades )
Here is my code to get the data and store into the array :
$key = $_POST['latestQuery'];
$requete = $bdd->prepare('SELECT url, title FROM articles WHERE title LIKE :key LIMIT 10');
$requete->execute(array('key' => '%'.$key.'%'));
$result_array[] = array();
foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
print_r($result_array[$search['title']] = $search);
}
And here this my table structure :
url | title
$search=ACDC | ACDC
Do you think there is a way to formate my array?
Remove print_r from a foreach:
$result_array = array();
foreach($requete->fetchAll(PDO::FETCH_ASSOC) as $search)
{
$result_array[$search['title']] = $search['url'];
}
print_r($result_array);
You can try this:
// testing array
$yourArray = array(
array(
'url'=>'?search=ABBA',
'title'=>'ABBA',
),
array(
'url'=>'?search=BABA',
'title'=>'BABA',
),
array(
'url'=>'?search=CBAA',
'title'=>'CBAA',
),
);
// solution
$myArr = array();
foreach ($yourArray as $key => $value) {
$myArr[$value['title']] = $value['url'];
}
echo "<pre>";
print_r($myArr);
Result is:
Array
(
[ABBA] => ?search=ABBA
[BABA] => ?search=BABA
[CBAA] => ?search=CBAA
)

PHP - Modify an array during foreach loop

public function getUserList($user_id){
$list_query = "SELECT ACTUAL_USER_ID FROM TABLE WHERE USER_ID = ".$user_id." ";
$result = parent::queryresult($list_query);
return $result;
}
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID']);
}
The loop outouts below
Array
(
[0] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
)
[1] => Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 122
)
)
)
How can I remove nested arrays and make it like below
Array
(
[0] => Array
(
[ACTUAL_USER_ID] => 133
)
[1] => Array
(
[ACTUAL_USER_ID] => 122
)
)
Use brackets [] to access array's elements
foreach ($result as $uresult){ //$result contains user_id
$userlist[] = $classObject->getUserList($uresult['USER_ID'])[0];
}
Edit: on different/old version of PHP you need to put array into variable first:
foreach ($result as $uresult){ //$result contains user_id
$row = $classObject->getUserList($uresult['USER_ID']);
$userlist[] = $row[0];
}
Change foreach statement as below
foreach ($result as $uresult){ //$result contains user_id
$res = $classObject->getUserList($uresult['USER_ID']);
if(isset($res[0]))
$userlist[] = $res[0];
}

Fetch all rows based on the query into an array and return single value

Fetch all rows based on the query into an array and return single value
Query database for data
//----------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); query
$array = mysql_fetch_row($result);
fetch result In Array
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
Result Will Be
Array
(
[0] => Array
(
[0] => status_site
[1] => 0
)
[1] => Array
(
[0] => title_site
[1] => Script
)
[2] => Array
(
[0] => keys_site
[1] =>
)
)
I need to make function that return element 0 to 1
ex: function getsetting (title_site){
return value script}
Replace the $arr[] = $arr2; with $arr[$arr2[0]] = $arr2[1];. That might solve your problem.

Categories