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
)
Related
I have some array like this
Array(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486"}
)
Here i want to add some data to at the end of each looping so data will look as follow.
Array(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name"=>"tiles" ,"hsn" =>"42424"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name"=>"wood","hsn" =>"63636"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name"=>"granite","hsn" =>"66656"}
)
I tried array push method but its created another index , instead of adding new data to last
below is my code.
$items = array();
$variations = array();
if ($purchaseOrderDetails->getOrderItems())
{
foreach ($purchaseOrderDetails->getOrderItems() as $key => $item)
{
$items[] = strval($item);
$variations[] = strval(new InventorySetVariation($item->getIsvid()));
}
}
Utility::ajaxResponseTrue("", array("po" => strval($purchaseOrderDetails), "items" => $items, "variations" => $variations));
Here I want to merge item and variations as one array .
how can I achieve it ?
Below is the example may help you to achieve similar goals of yours
<?php
$items = array(
0 => '{"puroriid":"3902598","purorid":"3901727","iid":"3927478"}',
1 => '{"puroriid":"3902599","purorid":"3901727","iid":"3927486"}',
2 => '{"puroriid":"3902600","purorid":"3901727","iid":"3927486"}'
); //Your Items
$itmesNew = [];
foreach($items as $val)
{
$newItem = json_decode($val,true);
$newItem['variation_name'] = 'test'; //New Items Append
$newItem['hsn'] = '123'; //New Items Append
$itmesNew[] = json_encode($newItem); //Add as json
}
echo "<pre>";
print_r($itmesNew);
?>
Output
Array
(
[0] => {"puroriid":"3902598","purorid":"3901727","iid":"3927478","variation_name":"test","hsn":"123"}
[1] => {"puroriid":"3902599","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
[2] => {"puroriid":"3902600","purorid":"3901727","iid":"3927486","variation_name":"test","hsn":"123"}
)
I have a multidimensional array.I want to extract this array through foreach loop and want to display in a unordered list. how to solve this. please help me. i am trying for 2 days but could not get any solution. i think i'm weak in loop.
Array
(
[id] => 1
[name] => Funny
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 1
[img_name] => fapore kapor nosto
)
)
)
)
Array
(
[id] => 4
[name] => Events
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 4
[img_name] => elo khushir eid
)
[1] => Array
(
[ci_cat_id] => 4
[img_name] => Eid e bari jacchi
)
)
)
)
i want the output like this
category name1:
1. test1
2. test2
3. test3
category name2:
1. test4
2. test5
3. test6
You need to use the array_column(). First of all you need to loop the array and get the category names, and also you need to get the img_name, for this you have to use the array_column and that function gives you the array of that img_name, so now again loop this new array and print the img_name.
Your array:
$arr = array(
array(
"id" => 1,
"name" => "Funny",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 1,
"img_name" => "fapore kapor nosto"
)
)
)
),
array(
"id" => 4,
"name" => "Events",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 4,
"img_name" => "elo khushir eid"
),
array(
"ci_cat_id" => 4,
"img_name" => "Eid e bari jacchi"
)
)
)
)
);
procedure:
foreach($arr as $val){
echo $val['name']."<br/>";
$i = 1;
$img_name = array_column($val['category_details']['get_everything'], 'img_name');
foreach($img_name as $v){
echo $i++.' - '.$v."<br/>";;
}
}
Output:
Funny
1 - fapore kapor nosto
Events
1 - elo khushir eid
2 - Eid e bari jacchi
Try this will may help you,
1) If you want array:
foreach ($array as $k=>$v){
foreach ($v['category_details']['get_everything'] as $key => $val){
$finalArray[$v['name']][] = $val['img_name'];
}
}
Output will look like this,
Array
(
[Funny] => Array
(
[0] => fapore kapor nosto
)
[Events] => Array
(
[0] => elo khushir eid
[1] => Eid e bari jacchi
)
)
2)If You want string :
foreach ($array as $k=>$v){
echo $v['name'].'<br/>';
$i=1;
foreach ($v['category_details']['get_everything'] as $key => $val){
echo $i.'. '.$val['img_name'].'<br/>';
$i++;
}
}
Output Will be,
Funny
1. fapore kapor nosto
Events
1. elo khushir eid
2. Eid e bari jacchi
try this one
foreach($array as $value) {
echo $value['name'];
foreach($value['category_details'] as $val) {
$i=1;
foreach($val as $v) {
echo $i++ . '. ' . $v['img_name'];
}
}
}
hope this help..
My Controller
function indexx() {
$emp['get_all_img'] = $this->model_bundle->get_all_img();
$t = $this->model_bundle->get_category();
$i = 1;
foreach ($t as $key => $data) {
//$emp['get_everything'][$key]['id'] = $data['id'];
$emp['get_everything'][$key]['name'] = $data['name'];
$emp['get_everything'][$key]['category_details'] = $this->get_category_wise_image($data['id']);
$i++;
}
$this->layout->view('bundle/add_bundle', $emp);
}
function get_category_wise_image($cat_id) {
$data = $this->model_bundle->get_category_wise_image($cat_id);
$i = 1;
foreach ($data as $key => $data) {
$emp['get_everything'][$key]['ci_cat_id'] = $data['ci_cat_id'];
$emp['get_everything'][$key]['bangla_caption'] = $data['bangla_caption'];
$emp['get_everything'][$key]['images_id'] = $data['images_id'];
$emp['get_everything'][$key]['thumnail'] = $data['thumnail'];
$i++;
}
//echo "<pre>";
//print_r($emp);
return $emp;
}
My Model
function get_all_img()
{
$this->db->select('id, bangla_caption, thumnail');
$query = $this->db->get('images');
return $query->result();
}
function get_category(){
$this->db->select('id, name');
$this->db->from('category');
$this->db->order_by('id');
$result = $this->db->get();
return $result->result_array();
}
function get_category_wise_image($id){
$this->db->select('category_images.id as id, img_id, category_images.cat_id as ci_cat_id, images.cat_id as im_cat_id, bangla_caption, name, thumnail, images.id as images_id');
$this->db->from('category_images');
$this->db->join('category','category.id = category_images.cat_id','left');
$this->db->join('images','images.id = category_images.img_id','left');
$this->db->where('category_images.cat_id',$id);
$result = $this->db->get();
return $result->result_array();
}
view(add_bundle.php)
foreach($get_everything as $tasks){
//echo "<pre>";
//print_r($tasks);
echo '<div class="cat_name">'. $tasks['name'].'</div>';
echo "<ul>";
foreach($tasks as $task){
foreach($task as $p){
foreach($p as $pr){
echo '<div height="50px">
<label><input type="checkbox" name="img_id[]" class="second" value="'.$pr['images_id'].'">';
echo '<img src="'.base_url()."uploads/".$pr['thumnail'].'" width="60px">"'.$pr['bangla_caption'].'"</label></div>';
}
}
}echo "</ul>";
}
I want to convert multi dimensional array in Php
I'm stuck in logic.. Kindly help
Thanks in advance
Current Produced array :
Array
(
[5316] => Array
(
[0] => Array
(
[PROD1] => color=black
)
[1] => Array
(
[PROD1] => paper=a1
)
[2] => Array
(
[PROD2] => color=metallic_silver
)
[3] => Array
(
[PROD2] => paper=a1
)
)
)
I want to convert this array into this form
Array
(
[5316] => Array
(
[PROD1] => Array
(
color => black
paper => a1
)
[PROD2] => Array
(
color => metallic_silver
paper => a1
)
)
)
If you can't hardcode that key to directly point to it, you can use reset() in this case, then grouped them inside a foreach accordingly. Example:
$array = array(
5316 => array(
array('PROD1' => 'color=black'),
array('PROD1' => 'paper=a1'),
array('PROD2' => 'color=metallic_silver'),
array('PROD2' => 'paper=a1'),
),
);
$grouped = array();
// point it to the first key which gives an array of those values
foreach (reset($array) as $key => $value) {
reset($value); // reset the internal pointer of the sub array
$key = key($value); // this return `PROD1, PROD2`
$grouped[$key][] = current($value); // current gives color=black, the values
}
$array[key($array)] = $grouped; // then reassign
echo '<pre>';
print_r($array);
Sample Output
You can try something like below.
$newArr = [];
$count = count($arr[5316]);
for($i = 0, $j = 1; $i < $count; $i += 2){
$color = explode('=', $arr[5316][$i]['PROD'.$j]);
$paper = explode('=', $arr[5316][$i+1]['PROD'.$j]);
$newArr[5316]['PROD'.$j] = array('color'=>$color[1], 'paper'=>$paper[1]);
$j++;
}
//To show output
print '<pre>';
print_r($newArr);
print '</pre>';
I have the following array:
Array
(
[0] => Array
(
[User] => Array
(
[firstname] => Chris
[lastname] => Willis
)
)
[1] => Array
(
[User] => Array
(
[firstname] => Test
[lastname] => Willis
)
)
...
I need it to be transformed into a structure similar to this:
Array
{
'Chris-Willis' => 0
'Test-Willis' => 1
....
What are some array functions to help to do this?
So it needs to be:
firstname-lastname => id
$grouped = array();
foreach ($users as $i => $user) {
$grouped["{$user['User']['firstname']}-{$user['User']['lastname']}"] = $i;
}
If the array is exactly as shown above, this should also do it:
$grouped = array_combine(array_map(function ($u) { return join('-', current($u)); }, $users), array_keys($users));
CakePHP has the Set::combine() method to help with such situations.
I'm assuming that you want the array values to be the database ID of the user, rather than the array index.
$users = $this->User->find('all', array(
'fields' => array('id', 'firstname', 'lastname'),
));
$usersMap = Set::combine(
$users,
array('%1$s-%2$s', '{n}.User.firstname', '{n}.User.lastname') // sprintf() formatting
'{n}.User.id',
);
foreach $original_array as $key=>$temp
{
$some_other_array[$temp['USER']['firstname']."-".$temp['USER']['lastname']] = $key;
}
The following code should do the trick
//$names is the name of your array
$namesId = array();
foreach ($names as $k=>$v)
{
$temp = $v["User"]["firstname"] . "-" . $v["User"]["lastname"];
$namesId[$temp] = $k;
}
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;
}