PHP foreach inside Array - php

I try to use foreach inside an array but I get error
my php code is :
<?php
$items = [
foreach ($model->galleries as $glrThm){
[
'url' => Url::home().$glrThm->Gallery_image,
'src' => Url::home().$glrThm->Gallery_imagethumb,
],
}
];
?>

Unfortunately, that construct/syntax is not allowed.
If you would like to use something like it then array_map() could be for you:
$items = array_map( function( $glrThm ){
return [
'url' => Url::home().$glrThm->Gallery_image,
'src' => Url::home().$glrThm->Gallery_imagethumb
];
}, $model->galleries );
If you need or wish to use foreach() then this is the proper syntax:
$items = [];
foreach ($model->galleries as $glrThm){
$items[] = [
'url' => Url::home().$glrThm->Gallery_image,
'src' => Url::home().$glrThm->Gallery_imagethumb
];
}

That syntax is not allowed.
First create your array
<?php
$items = [];
Then loop over your other array picking the items you want to transfer
foreach ($model->galleries as $glrThm){
$items[] = ['url' => $glrThm->Gallery_image,
'src' => $glrThm->Gallery_imagethumb,
];
}
?>

Related

Calling values from an array using an array or string - php

I have a problem writing a code in which I can arrive at the values, but using text or an array
Suppose this Array:
$array = [
'name' => 'any Name',
'settings' => [
'app' => 'Spy',
'location' => 'Earth',
'locale' => 'en'
]
];
and i want to get app value
default code:
echo $array['settings']['app'];
But this method is not working because I cannot write the parentheses [] [] in my case
I want a method similar to this:
$handle = 'app, name';
echo $array[$handle] ;
or
$handle = ['settings']['app'];
echo $array[$handle];
I know that the code is wrong, but an example
I hope that the idea has arrived and that there is a solution.
Could it be something like that?
<?php
$array = [
'name' => 'any Name',
'settings' => [
'app' => 'Spy',
'location' => 'Earth',
'locale' => 'en'
]
];
$str = 'settings|app'; // this is string you have
foreach (explode('|', $str) as $key) {
if (!isset($output)) {
$output = $array[$key];
} else {
$output = $output[$key];
}
}
echo $output; // spy

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]);

PHP get the name of arrays in multidimensional array

I have a simple multidimensional array with two other arrays in it.
<?php
$data = array(
'first_array' => array(
'name' => 'Test1',
'description' => '...',
),
'second_array' => array(
'title' => 'Test2',
'description' => '...',
)
);
?>
And I have a simple foreach array like this:
function show($data, $id){
foreach ($data as $course) {
}
}
How can I display (and get) the name of the array in every iteration (I mean if it is 'first_array' or 'second_array', not the name fields in the arrays).
Use key=>val syntax
foreach ($data as $key=>$course) {
echo $key;
}
use this syntax for foreach :
foreach ($data as $name => $course) {
//do sth
}

PHP - How to create such array?

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.

Adding a foreach inside of an array - PHP

Basically I want to add a dynamic array inside of another array, here's my array :
$myarray = array(
'options' => array( ),
);
And here's the dynamic array :
$page = array(
array('id' => '1' ,'title'=>'Page1' ),
array('id' => '2' ,'title'=>'Page2' )
);
I want to $myarray to be like this :
$myarray = array(
'options' =>
array('1' => 'Page1' ,'2'=>'Page2' ),
);
Here's what I tried :
foreach ($page as $key => $value) {
$myarray['options'][]=array(
"".$value['id']."" =>"".$value['title'].""
);
}
Any help with this? Thanks.
Here's a codepad demo
$myarray = [];
foreach($page as $key => $value) {
$myarray['options'][$value['id']] = $value['title'];
}
Just try with:
$myarray['options'] = array_reduce($page, function($options, $item){
$options[$item['id']] = $item['title'];
return $options;
});

Categories