how can i fill following type array dynamicly in for loop
array('items'=>array(
array('label'=>'News', 'url'=>array('/site/index')),
array('label'=>'News2', 'url'=>array('/site/2')),
));
I am new in programming
thanks for help
Try this:
$arr = array();
for($i = 1; $i <= $count; $i++) {
$arr[] = array(
'label' => 'News'.($i > 1 ? $i : ''),
'url' => $i == 1 ? '/site/index' : '/site/'.$i
)
}
$result = array('items' => $arr);
And the resulting array will be in the form:
array('items' => array(
array(
'label' => 'News',
'url' => '/site/index'
),
array(
'label' => 'News2',
'url' => '/site/2'
),
array(
'label' => 'News3',
'url' => '/site/3'
),
array(
'label' => 'News4',
'url' => '/site/4'
)
));
..depending on the $count variable.
for($i = 0; $i < $items; $i++) { //where $items is number of news items
if($i == 0)
$value = "Index";
else
$value = $i+1;
$ar["items"]["News".$i] = $value;
}
You can access the array by square brackets, by both alphanumerical and purely numerical keys. Anyway I suggest reading a basic php course.
use for to loop like :
$items=array();
for($i=1;$i<=$max_count;$i++){
$element = array('label'=>'news'.$i,'url'=>'/site/index'.$i);
$items[] = $element;
}
Related
I am trying to bulk upload in elastic search and i am getting this error for every record i am trying to insert.
Please help me with this.
{"took":2828,"errors":true,"items":[{"index":{"_index":"abc","_type":"abc","_id":"0","status":400,"error":{"type":"mapper_parsing_exception","reason":"failed to parse","caused_by":{"type":"not_x_content_exception","reason":"Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes"}}}}]}
This is the code i am using
I am using 5.3 and elasticsearch driver 1.4
<?php require_once "/var/www/ElasticSearch/models/ElasticSearchModels.php"; $params = array(); $ids = array(); for($i=0;$i<10;$i++){ $ids[] = $i; $params[] = array("here"=>"here","temp"=>"temp","pr"=>$i); } $elasticSearch = new ElasticSearch(); $elasticSearch->saveInElasticSearchBulk("products_staging","products_staging",$ids,$params); ?>
You're not constructing the $params array correctly, it should look like this instead:
$params = array();
for($i = 0; $i < 10; $i++){
$params['body'][] = array(
'index' => array(
'_index' => 'products_staging',
'_type' => 'products_staging',
'_id' => $i
)
);
$params['body'][] = array(
'here' => 'here',
'temp' => 'temp',
'pr' => $i
);
}
$elasticSearch = new ElasticSearch();
$elasticSearch->saveInElasticSearchBulk($params);
I solved this issue since i was using ElasticSearch php driver 1.4. The syntax for the bulk api is quite different.
$params = array();
for($i = 0; $i < 10; $i++){
$params['body'][] = array(
'index' => array(
'_index' => 'products_staging',
'_type' => 'products_staging',
'_id' => $i
)
);
$params['body'][] = json_encode(array(
'here' => 'here',
'temp' => 'temp',
'pr' => $i
);)
}
$elasticSearch = new ElasticSearch();
$elasticSearch->saveInElasticSearchBulk($params);
Is there a better/more efficient way to loop through this data?
I need to loop through the array data with the 'Name' first and the 'ListID' second but the external API request generates the array as per the code below (the other way round).
// Array Data
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
// Generate Array Varaibles
foreach($csList as $array => $values) {
foreach($values as $k => $v) {
for($i = 1; $i < count($csList); $i++) {
$csListData[$k][] = $v;
}
}
}
// Loop Data
for($i = 0; $i < count($csList); $i++) {
echo $csListData['Name'][$i].'<br>';
echo $csListData['ListID'][$i].'<br>';
}
It's not at all clear why you're rearranging the data. Loop over the array and access whatever keys you want in whatever order you want.
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
foreach ($csList as $item) {
echo $item['Name'].'<br>';
echo $item['ListID'].'<br>';
}
Your inner for loop is useless. You can use the $array key to get your array as wanted :
foreach($csList as $array => $values) {
foreach($values as $k => $v) {
$csListData[$k][$array] = $v;
}
}
// Loop Data
for($i = 0, $c = count($csList); $i <$c; $i++) {
echo '<br>';
echo $csListData['Name'][$i].'<br>';
echo $csListData['ListID'][$i].'<br>';
}
Also, moving the count() out of the check will avoid to count at every iteration of the loop.
// Array Data
$csList = array(
array(
'ListID' => 'BGERFwQTrHoseE4sweebqwyAxuJ9YU',
'Name' => 'Monthly Newsletter Subscribers'
),
array(
'ListID' => 'kHdUQMbELgMyojuATz9Dsbxz3WViVo',
'Name' => 'Special Mailout'
)
);
You can do as follow:
$newCsList = array();
$newCsList = array_map(function ($val){
return array_reverse($val,true);
},$csList);
The result is like:
**Array (
[0] => Array (
[Name] => Monthly Newsletter Subscribers
[ListID] => BGERFwQTrHoseE4sweebqwyAxuJ9YU
)
[1] => Array (
[Name] => Special Mailout
[ListID] => kHdUQMbELgMyojuATz9Dsbxz3WViVo
)
)**
But for taking each element you can do:
$newCsList = array();
$newCsList = array_map(function ($val){
$my_test_ary = array_reverse($val);
echo $my_test_ary['Name'].'<br/>'.$my_test_ary['ListId'];
},$csList);
I have this complicated array.
<?php
require_once('core/connect.php');
require_once('core/database.class.php');
require_once('core/controller.class.php');
require_once('core/settings.class.php');
$database = new Database($db);
$controller = new Controller($db);
$settings = new Settings($db);
$database->selectAll('SELECT * FROM bookings_calendar');
$result = $database->fetchAll();
$count = 0;
$arr = array();
foreach($result as $row)
{
$arr['booking_date'][$count] = $row['booking_date'];
$arr['new'][$count] = $row['new'];
$arr['completed'][$count] = $row['completed'];
$arr['accepted'][$count] = $row['accepted'];
$arr['cancelled'][$count] = $row['cancelled'];
$count++;
}
header("content-type: application/json");
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => $arr['new'][0] . ' new',
'start' => $arr['booking_date'][0],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][0]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['new'][1] . ' new',
'start' => $arr['booking_date'][1],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][1]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
array(
'id' => 111,
'title' => $arr['new'][2] . ' new',
'start' => $arr['booking_date'][2],
'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][2]),
'color' => '#F7F8E0',
'textColor' => 'black'
),
));
?>
As you can see i can only put values manually by changing index, however i'd like to put all elements into that array automatically, but unfortunately i cannot use a foreach loop within an array. And my php skills are not that good, so im searching for some help.
Any help really appreciated. Thanks!
Get rid of the foreach and use a for loop.
$arr = array();
for($i=0; $i < count($result); $i++) {
$arr[$i]['title'] = $result[$i]['new'] . ' new';
$arr[$i]['whatever'] = $result[$i]['whatever'];
}
return json_encode($arr);
I have an array like this:
array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
I want to merge all of the nested options arrays' name/prices into one, so it'll be like this:
array(
'red' => '2',
'blue' => '3',
'small' => '5',
'large' => '10'
);
I have a feeling this is very simple, but anything I try seems too convoluted. Any help would be appreciated.
...and yes, I just posted almost the same question not too long ago. This is a bit different, and what I meant to ask in the first place - oops, sorry.
I'm not sure if this can be done with internal methods such as array_merge(), array_combine(), etc since your structure seems quite special. But how about iterating over the array and building a new one yourself?
function customRearrange($arr) {
$result = array();
foreach ($arr as $group) {
foreach ($group['options'] as $option) {
// prevents values from being overwritten, uncomment if unwanted
if (!array_key_exists($option['name'], $result))
$result[ $option['name'] ] = $option['price'];
}
}
return $result;
}
You need to decide how you will handle collisions, anyway here is same which will give you right direction:
$newArray = array();
foreach ($array as $i => $item)
foreach ($item['options'] as $j => $option)
$newArray[$option['name']] = $option['price'];
Here's another way, assuming the array has been assigned to the variable $a:
<?php
for ($i = 0; $i < count($a); $i++) {
$key = $a[$i]['name'];
$options = $a[$i]['options'];
for ($j = 0; $j < count($options); $j++) {
$optkey = $options[$j]['name'];
$prices[$optkey] = $options[$j]['price'];
}
}
print_r($prices);
Iterate through "options" in the nested array and create a new array :
<?php
$arr = array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
$group = array();
foreach($arr as $a){
foreach($a['options'] as $op){
$group[$op['name']] = $op['price'];
}
}
print_r($group);
?>
public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF');
$cpt=1;
foreach($this->items as $item){
$arr1[] = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$cpt++;
}
return array_merge($arr,$arr1[0],$arr1[1]);
}
This returns array like that:
Array
(
[cmd] => _cart
[business] => some#mail
[no_shipping] => 1
[upload] => 1
[return] => url1
[cancel_return] =>url2
[no_note] => 1
[currency_code] => EUR
[bn] => PP-BuyNowBF
[item_number_1] => 28
[item_name_1] => item_name_1
[quantity_1] => 1
[amount_1] => 5
[item_number_2] => 27
[item_name_2] => item_name_2
[quantity_2] => 1
[amount_2] => 30
)
The problem is that in return $arr1[0] and $arr1[1] are hardcoded. And if in loop i have more than 2 arrays, lets say 0,1,2,3 ans so on, this code won't work. Any idea? Maybe my logic is compleatly wrong...
There's no need to create arrays in your loop - just add new keys directly to the first array:
public function getCheckoutForm(){
$arr = array(
'cmd' => '_cart',
'business' => 'some#mail',
'no_shipping' => '1',
'upload' => '1',
'return' => 'url',
'cancel_return' => 'url1',
'no_note' => '1',
'currency_code' => 'url2',
'bn' => 'PP-BuyNowBF'
);
$cpt=1;
foreach($this->items as $item){
$arr['item_number_'.$cpt] = $item['item_id'];
$arr['item_name_'.$cpt] = $item['item_name'];
$arr['quantity_'.$cpt] = $item['item_q'];
$arr['amount_'.$cpt] = $item['item_price'];
$cpt++;
}
return $arr;
}
I would probably do something like
$count = count($arr1);
for($i=0;$i<$count;$i++){
$arr = array_merge($arr,$arr1[$i]);
}
return $arr;
I hope, I understood, what you mean ^^
foreach ($i = 0, $n = count($arr1); $i < $n; $i++) {
$arr = array_merge($arr, $arr1[$i]);
}
return $arr;
You could do the merge in every iteration:
foreach($this->items as $item){
$temp_arr = array(
'item_number_'.$cpt.'' => $item['item_id'],
'item_name_'.$cpt.'' => $item['item_name'],
'quantity_'.$cpt.'' => $item['item_q'],
'amount_'.$cpt.'' => $item['item_price']
);
$arr = array_merge($arr,$temp_arr)
$cpt++;
}
which has the advantage that you could possibly get $temp_arr from a function,
or just add all the elements to one array:
foreach($this->items as $item){
$arr['item_number_'.$cpt.''] => $item['item_id'];
$arr['item_name_'.$cpt.''] => $item['item_name'];
$arr['quantity_'.$cpt.''] => $item['item_q'];
$arr['amount_'.$cpt.''] => $item['item_price'];
$cpt++;
}
do this
$count = count($data);
$sum = 1;
$arr = [];
for($i=0;$i<$count;$i++){
$temp = $arr;
if($i == $count - 1){
$sum = 0;
}
$arr = array_merge($temp,$data[$i + $sum]);
}
return $arr;