I have a array in PHP (like example) and I need to get the value tipo from the index, whitch is the first parameter, codigo_tipo. I tried a lot of times, but no one works. Thanks.
$this->conteudo['tipos'] = array(array('codigo_tipo' => '0', 'tipo' => 'NotÃcias'), array('codigo_tipo' => '1', 'tipo' => 'Informativos'), array('codigo_tipo' => '2', 'tipo' => 'Agenda'));
If I understood you correctly:
$search = 0; // codigo_tipo
foreach ($this->conteudo['tipos'] as $key => $value)
{
if ($value['codigo_tipo'] == $search)
{
echo $value['tipo']; // Noticias
}
}
You have a nested array there, so you need to address each step separately.
$this->conteudo['tipos'][0]['tipo']; // <-- 'Noticias'
Not sure this is what you want, but this iterates through the array:
<?php
$this->conteudo['tipos'] = array(array('codigo_tipo' => '0', 'tipo' => 'NotÃcias'), array('codigo_tipo' => '1', 'tipo' => 'Informativos'), array('codigo_tipo' => '2', 'tipo' => 'Agenda'));
foreach ($this->conteudo['tipos'] as $elem) {
echo "codigo_tipo: ".$elem['codigo_tipo']." - tipo: ".$elem['tipo']."\n";
}
?>
Related
I'm trying to insert multiple rows into MySQL using the 'InsertBatch' function. However, I am unable to make it work. I'm new to this, and I'm not sure if I'm doing it correctly.
I'm using input and select fields with $is data and a table with $tmp data. I used foreach and for statements to get the $tmp_data on the table. An array push() was also used to merge the data into an array.
public function Add_Fees_Matrix() {
$fm_model = new Mod_Fees_Matrix();
$data = [];
//input and select type
$is_data = [
'fm_code' => $this->request->getPost('fm_code'),
'sy_id' => $this->request->getPost('sy_id'),
'dept_id' => $this->request->getPost('dept'),
'gl_id' => $this->request->getPost('gl_id'),
'ppl_id' => $this->request->getPost('ppl_mode')
];
//table
$tmp_data = [
'fcp_description' => $_POST['fcp_description'],
'fmf_amount' => $_POST['fmf_amount']
];
foreach ($tmp_data as $k => $v) {
for($i = 0; $i < count($v);$i++) {
array_push($data, $is_data);
$data[$i][$k] = $v[$i];
}
}
echo "<pre>";
var_export($data);
$fm_model->insertBatch($data);
}
In my output, it generates four arrays. However, only the first two arrays are considered necessary. I think the problem is caused by the array push() function.
Here's the output of var_export():
array (
0 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
'fcp_description' => 'INSTITUTIONAL DEVELOPMENT FEE',
'fmf_amount' => '123',
),
1 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
'fcp_description' => 'MATRICULATION',
'fmf_amount' => '1230',
),
2 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
),
3 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
),
)
Upon clicking a button, can someone help me to insert the data on my database?
This seems to work in my problem.
public function Add_Fees_Matrix() {
$fm_model = new Mod_Fees_Matrix();
$data = [];
$tmp_data = [
'fcp_description' => $this->request->getPost('fcp_description'),
'fcp_amount' => $this->request->getPost('fmf_amount')
];
foreach ($tmp_data as $k => $v) {
for($i = 0; $i < count($v);$i++) {
$data[$i]['fm_code'] = $this->request->getPost('fm_code');
$data[$i]['sy_id'] = $this->request->getPost('sy_id');
$data[$i]['dept_id'] = $this->request->getPost('dept');
$data[$i]['gl_id'] = $this->request->getPost('gl_id');
$data[$i]['ppl_id'] = $this->request->getPost('ppl_mode');
$data[$i][$k] = $v[$i];
}
}
$fm_model->insertBatch($data);
echo "<pre>";
var_export($data);
}
I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for or a foreach is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);
How do I check if any of the keys in foreach loop exists in another array's value ?
Array 1 I want to check
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
And the Array 2 which Array 1 should be compared to
$reserved_words = array('b');
What I want is to check whether the conditional check is TRUE to apply specific actions. My code looks like this now:
foreach( $array1 as $key => $value )
{
// Check for reserved words
if( in_array($key, $reserved_words)
{
// Some action
}
// Code...
}
I can't find anything similiar to array_key_exists, probably I am missing something.
I want to check it by simply doing this:
if( array_value_exists($value, $reserved_words) )
But the problem is that no array_value_exists function is available.
You forgot first the as keyword in your foreach header and you missed a ) in your if statement.
So this should work:
<?php
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
$reserved_words = array('b');
foreach( $array1 as $key => $value ) {
//^^Here 'as' keyword
if( in_array($key, $reserved_words)) {
echo $key; //^Here ')' closed if statement
}
}
?>
$array1 = array(
'a' => '1',
'b' => '2',
'c' => '3',
);
$reserved_words = array('b');
>>> array_intersect_key($array1, array_flip($reserved_words));
=> [
"b" => "2"
]
you are missing the 'as' keyword. Please put the code like below
foreach($array1 as $key => $val){
if(in_array($key, $reserved_words)){
echo "yes";
} else {
echo "no";
}
}
I have the following multidimensional array.
$arr = array(
0 => array(
'id' => 1,
'title' => 'title1',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb1',
'custodian' => 'custodia1',
'tags' => 'tag1',
'active' => 'Y',
),
1 => array(
'id' => '2',
'title' => 'title2',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb2',
'custodian' => 'custodia2',
'tags' => 'tag1,tag2',
'active' => 'Y',
),
2 => array(
'id' => '3',
'title' => 'title3',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb3',
'custodian' => 'custodia3',
'tags' => 'tag1,tag2,tag3',
'active' => 'Y',
),
);
I need to filter the array so that only the arrays with "tag2" in the tags value are displayed.
I've looked at array_filter but just can't get my head around it.
Here is my attempt but it doesn't work at all. not sure what I'm doing wrong.
$filterArr = array_filter($arr, function($tag) {
return ($tag['tags'] == 'tag2');
});
The simplest way is to use foreach loop and in the body of loop check for 'tag2'
If you need to delete all rows without tag2 in tags you can use next loop:
foreach ($arr as $key => $value) {
if (!preg_match('/\btag2\b/',$value['tags'])) {
unset($arr[$key]);
}
}
you could use array_filter and provide the right callback
$result = array_filter($arr,function($t){
return in_array('tag2',explode(',',$t['tags']));
});
array_filter takes each element of the array and passes it to the specified function, in that function you need to return true or false, true if it should stay in and false if it should be filtered out
Use explode and in_array to check for tag2
$filteredArray = array_filter($arr, "filterTag");
function filterTag($arrayElement) {
return in_array("tag2",explode(",",$arrayElement["tags"]));
}
your attempt does not work because some of your "tags" contain other words than tags2, like tag1,tag2,tag3 doing a simple == comparison does not search a string for another string
$resultArr = array();
foreach($arr as $curr)
{
$tagsData = explode(',',$curr['tags']);
if(in_array('tag1',$tagsData)
$resultArr[] = $curr;
}
$resultArr is the resulting array containing the arrays with tags having tag1
For example, I have multidimensional array as below:
$array = array (
0 =>
array (
'id' => '9',
'gallery_id' => '2',
'picture' => '56475832.jpg'
),
1 =>
array (
'id' => '8',
'gallery_id' => '2',
'picture' => '20083622.jpg'
),
2 =>
array (
'id' => '7',
'gallery_id' => '2',
'picture' => '89001465.jpg'
),
3 =>
array (
'id' => '6',
'gallery_id' => '2',
'picture' => '47360232.jpg'
),
4 =>
array (
'id' => '5',
'gallery_id' => '2',
'picture' => '4876713.jpg'
),
5 =>
array (
'id' => '4',
'gallery_id' => '2',
'picture' => '5447392.jpg'
),
6 =>
array (
'id' => '3',
'gallery_id' => '2',
'picture' => '95117187.jpg'
)
);
How can I get key of array(0,1,2,3,4,5,6)?
I have tried a lot of examples, but nothing has worked for me.
This is quite simple, you just need to use array_keys():
$keys = array_keys($array);
See it working
EDIT For your search task, this function should do the job:
function array_search_inner ($array, $attr, $val, $strict = FALSE) {
// Error is input array is not an array
if (!is_array($array)) return FALSE;
// Loop the array
foreach ($array as $key => $inner) {
// Error if inner item is not an array (you may want to remove this line)
if (!is_array($inner)) return FALSE;
// Skip entries where search key is not present
if (!isset($inner[$attr])) continue;
if ($strict) {
// Strict typing
if ($inner[$attr] === $val) return $key;
} else {
// Loose typing
if ($inner[$attr] == $val) return $key;
}
}
// We didn't find it
return NULL;
}
// Example usage
$key = array_search_inner($array, 'id', 9);
The fourth parameter $strict, if TRUE, will use strict type comparisons. So 9 will not work, you would have to pass '9', since the values are stored as strings. Returns the key of the first occurence of a match, NULL if the value is not found, or FALSE on error. make sure to use a strict comparison on the return value, since 0, NULL and FALSE are all possible return values and they will all evaluate to 0 if using loose integer comparisons.
Try this , I think it will help you.
foreach ($array as $key=>$value)
{
echo $key.'<br/>';
echo $value['id'].'<br/>';
echo $value['gallery_id'].'<br/>';
echo $value['picture'].'<br/><br/>';
}
sometimes it is to easy to find ;)
array_keys($array);
array_keys
Probably http://php.net/manual/en/function.array-keys.php ?
Convert your double dimensional array on your own:
$tmp = null
foreach($array as $key => $value) {
$tmp[] = $key;
}
print_r($tmp);
You mean something like this:
function getKeys($array)
{
$resultArr = array();
foreach($array as $subArr) {
$resultArr = array_merge($resultArr, $subArr);
}
return array_keys($resultArr);
}