Get ID from array and put it on another array codeigniter - php

Here's my code
function ...($id){
$data = array(
'name' => $this->input->post('name'),
'id' => $id
);
$data2 = array(
'inv_id' = $data['id']
);
}
I couldn't get the value of the id from the first array($data).
Is it possible to get the value of the key id from the first array($data) to the second array

while assigning array elements you must use '=>' operator'
like below: -
$data2 = array(
'inv_id' => $data['id']
);

Please use separator '=>' for the associative arrays.
Example:
$data2 = array(
'inv_id' => $data['id']
);

function ...($id){
//changes in the line below.
$inp_arr = ['name' => $this->input->post('name'),'id' => $id];
$some_other_arr = array(
'inv_id' = $inp_arr['id']
);
}
Edit 1:
//it is =>
'inv_id' => $inp_arr['id'] //pointed out in one of the answer.

Related

How can I delete value in the array by a condition on the php?

My first array like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
My second array like this :
$photo = array('cover1'=>'chelsea.jpg', 'cover2'=>'arsenal.jpg');
If value of the second array is not inside the first array, it will remove the value from the second array
Based on the above example, because arsenal.jpg is not inside in the first array then it will deleted
So I want the new array from $photo is like this :
$photo = array('cover1'=>'chelsea.jpg');
I give another example. For example my $photo array like this :
$photo = array('cover1'=>'madrid.jpg', 'cover2'=>'barcelona.jpg');
Then the new array to be like this :
$photo = NULL
Because it's not inside $photoList array
How can I do it?
You could use array_filter() to reduce the data, based on the array_column() of $photoList:
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo)) $photo=null; // to transform empty array to null.
var_dump($photo);
Outputs :
array(1) {
["cover1"]=>
string(11) "chelsea.jpg"
}
Or NULL for the second example.
Note that you also could extract array_column from the anonymous function, and pass it with use() :
$col = array_column($photoList, 'name') ;
$photo = array_filter($photo, function($item) use ($col) {
return in_array($item, $col) ;
});
Edit to reindex keys :
$idx = 1 ;
foreach ($photo as $k => $v) {
unset($photo[$k]);
$photo['cover'.$idx++]=$v;
}
Simply use the Php functions: array_intersect and array_column:
$photo = array_intersect($photo, array_column($photoList, 'name')) ?: null;
Try
<?php
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$photo = array('cover1'=>'chelsea.jpg', 'cover2'=>'arsenal.jpg');
foreach ($photo as $key => $value)// loop in $photo array
{
if(!in_array( $value ,array_column($photoList, 'name')))//check if $photoList array has $value in column 'name'
{
unset($photo[$key]);//unset element
}
}
print_r($photo);
?>
output:
Array ( [cover1] => chelsea.jpg )
update : code optimised by Progrock
$photoListNames = array_column($photoList, 'name');
foreach($photo as $key => $value)
if(!in_array($value, $photoListNames))
unset($photo[$key]);

Adding data to array through loop php

I have a problem where I am getting data from database and need to put that in an array. The array is associative and I am not sure about this practice so I thought I should ask the community. Is this the correct way of adding data to array? The array is for the radio buttons that will be provided to the helper class in prestashop. The array structure is important. This is the var_dump array structure which I have in $options_break2.
$options_value = array();
$options = array();
for($z=0; $z<sizeof($options_break2); $z++)
{
$options_value = array_push($options_value,
array(
"id" => $options_break2[$z],
"name" => $options_break2[$z],
"label" => $options_break2[$z],
)
);
}
$options = array_push($options, $options_value);
What I want is that the array should contain something like:
$example = array(
array(
'id_option' => 'some value',
'name' => 'some value',
),
array(
'id_option' => 'some value',
'name' => 'some value',
),
);
Actually you don't need to use array_push and array() if your PHP version is above 5.6, and you can improve your loop by using the foreach loop:
$options_value = [];
foreach ($options_break2 as $opt) {
$options_value[] = [
"id_option" => $opt, // some_value
"name" => $opt // some_value
];
}
$options = $options_value; // you don't really need this

How to assign array position to a variable for posterior use?

I got an array like this:
array(
'name' => 'array1',
'content' => array(
'name' => 'array2',
'content' => array(
'name' => 'array3',
'content' => array(...)
)
)
)
I want to insert data in the third array but don't wanna type something this length:
$array['content']['content']['content']... = 'something';
because I use it inside diferent foreach and it will become to long.
I try to assign the array into a variable like:
$array['content']['content']['content'] = array();
$content3 = $array['content']['content']['content'];
and then:
$content3['content4'] = 'something';
but doesn't store 'content4', any solution to this?
Use & to make content3 reference to $array['content']['content']['content']:
$array['content']['content']['content'] = array();
$content3 = &$array['content']['content']['content'];
$content3['content4'] = 'something';

Use Result of Aggregation MongoDB in PHP

I have this code:
$data = $collection->aggregate(
array(
'$group'=> array(
'_id' => $fn,
'massi' => array(
'$max' => $dnameth_value
)
)
)
);
I execute this query and I want to obtain only MAX Value, and use this in variable.
I tried this code :
$data=$collection->aggregate(array( '$group'=> array('_id'=>$fn,'massi'=>array('$max'=>$dnameth_value))));
var_dump( $data['result'] );
$func = function($value) {
return $value->massi;};
$massi = array_map($func, $data['result']);
var_dump($massi);
Output in the image attach
When you execute the query, the return value of the aggregate() helper method is an array with two elements: ok with a value of double(1) as well as a result element containing an array of all the documents that made it through the whole pipeline.
For instance, if you want to group all the documents by the field my_key and you want to obtain the maximum dnameth_value from that group, and you execute this aggregation operation
<?php
$m = new MongoClient;
$collection = $m->test->collection;
$fn = '$my_key';
$dnameth_value = '$dnameth_value'
$data = $collection->aggregate(
array(
'$group'=> array(
'_id' => $fn,
'massi' => array(
'$max' => $dnameth_value
)
)
)
);
var_dump( $data['result'] );
?>
you should expect the result array from $data['result'] to come in the following form (for example):
…
array (
'_id' => 'value',
'massi' => double(13),
),
array (
'_id' => 'other_value',
'massi' => double(9),
),
array (
'_id' => 'another_value',
'massi' => double(4),
),
…
Note: Because the aggregation framework returns all of its results as one document over the network, the full result is limited to 16MB. There are also memory limits internally, so it is always wise to restrict the data coming through the pipeline with an operator as soon as you can.
So, with your request, you basically would want to map all the massi values from the array into another array variable using array_map():
<?php
$m = new MongoClient;
$collection = $m->test->collection;
$fn = '$my_key';
$dnameth_value = '$dnameth_value'
$data = $collection->aggregate(
array(
'$group'=> array(
'_id' => $fn,
'massi' => array(
'$max' => $dnameth_value
)
)
)
);
var_dump( $data['result'] );
$func = function($value) {
return $value['massi'];
};
$massi = array_map($func, $data['result']);
var_dump($massi);
?>
Now, suppose you are grouping all the documents in the collection then specify an _id value of null to calculate accumulated values for all the input documents as a whole. The resulting array will have one element which you can access by its index:
<?php
$m = new MongoClient;
$collection = $m->test->collection;
$fn = 'null';
$dnameth_value = '$dnameth_value'
$data = $collection->aggregate(
array(
'$group'=> array(
'_id' => $fn,
'massi' => array(
'$max' => $dnameth_value
)
)
)
);
var_dump( $data['result'] );
$massi = $data['result'][0]['massi'];
var_dump($massi);
?>

Check if an array of an array contains a certain string

I'm checking to make sure an array of arrays does not contain certain strings before adding any new child arrays to the parent array
I want to make sure that if an array with the same website and condition exists a new child array will not be added to the parent array.
e.g. in this example the $newArr must not be inserted in to the array $arr because their already exists an array with the same website and condition.
$arr = array(
array(
'website' => 'amazon',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
),
array(
'website' => 'abe',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
);
$newArr = array(
'website' => 'amazon',
'price' => 60,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
I'm looking for an easy solution as using the function in_array on the parent array is not enough.
code so far
$arr = array();
foreach($table->find('tr.result') as $row){
if(($website = $row->find('a img',0))
&& ($price = $row->find('span.results-price a',0))
&& ($location = $row->find('.results-explanatory-text-Logo'))
&& ($link = $row->find('a',0))){
$website = str_replace( array('.gif','.jpg','.png'), '', basename($website->src));
$price = floatval(trim(str_replace(',', '', $price->innertext), "£"));
$location = "uk";
$link = $link->href;
$arr[] = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
}
}
You loop over $arr each time to look for $website and $condition (always 'new'?) or you can keep a secondary array of the found keys. If you're starting with an empty $arr each time, the second approach will work and be faster.
$arr = array();
$keys = array();
foreach($table->find('tr.result') as $row){
if(...){
...
$condition = 'new'; // set as needed
// track seen keys
$key = $website . '|' . $condition; // assumes neither field contains '|'
if (!isset($keys[$key])) {
$keys[$key] = true;
$arr[] = array(...);
}
}
}
I hope the comments in the below code speak for themselves... I'm not a PHP pro, and this is probably not the most elegant way, but I believe the logic makes sense. Obviously the $new_array object has some variables that aren't declared but it's for example only.
I hope that helps and that no one down votes me :)
<?php
// Original array
$arr = array();
foreach($result as $row) {
// Get the new array as an object first so we can check whether to add to the loop
$new_array = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
// If the original array is empty there's no point in looping through it
if(!empty($arr)) {
foreach($arr as $child) {
// Check through each item of the original array
foreach($new_array as $compare) {
// Compare each item in the new array against the original array
if(in_array($compare, $child)) {
// if there's a match, the new array will not get added
continue;
}
}
}
}
// If there's no match, the new array gets added
$arr[] = $new_array;
}
?>

Categories