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;
});
Related
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'=>'liverpool.jpg', 'cover2'=>'city.jpg');
My code like this :
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo))
$photo=null;
If I run : echo '<pre>';print_r($photo);echo '</pre>';, the result like this :
Array
(
[cover2] => city.jpg
)
I want the result like this :
Array
(
[cover1] => city.jpg
)
So if there is no cover1, the cover2 changed to be cover1
How can I do it?
You could re-index the keys like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg'
),
array(
'id' => 2,
'name' => 'mu.jpg'
),
array(
'id' => 3,
'name' => 'city.jpg'
)
);
$photo = array('cover1'=>'liverpool.jpg', 'cover2'=>'city.jpg');
$photo = array_filter($photo, function($item) use ($photoList) {
return in_array($item, array_column($photoList, 'name')) ;
});
if (empty($photo)){
$photo = null;
} else {
$idx = 1 ;
foreach ($photo as $key => $value) {
unset($photo[$key]);
$photo['cover'.$idx++] = $value;
}
}
print_r($photo);
Outputs :
Array
(
[cover1] => city.jpg
)
I'm not sure about what you really need. Assuming you want to do that recursively, I hope this helps:
$label = 'cover';
$index = 1;
$a_keys = array_keys($photo);
$new_photo = [];
foreach($a_keys AS $k=>$v){
$new_photo[$label.$index] = $photo[$k];
$index++;
}
$photo = $new_photo;
It will rewrite your array with wanted naming style.
How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?
Example:
Input:
$input = array('Orange','Apple','Banana');
Expected Output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
This is my code:
$categories = array('Orange','Apple','Banana');
$count = count($categories);
for($i=0;$i<=$count;$i++){
if(isset($categories[$i+1])){
$parent = $categories[$i+1]; // parent
$categories[$i+1]=array(
'name' => $categories[$i+1],
'sub_category' => array('name' => $categories[$i])
);
}
}
$categories = $categories[$count-1];
var_dump($categories);
My code is sloppy and I also get the following incorrect output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
);
Edit 1:
The problem/solution provided here does not seem to be answering my question.
You could use simple recursion technique:
function toNestedArray(array $input, array $result = [])
{
$result = ['name' => array_pop($input)];
if (count($input)) {
$result['sub_category'] = toNestedArray($input, $result);
}
return $result;
}
$categories = array('Orange','Apple','Banana');
$count = count($categories);
$categories2=array();
for($i=$count-1;$i>0;$i--){
if($i-2>-1){
$categories2=array(
'name'=>$categories[$i],
'sub_category'=>array('name'=>$categories[$i-1],'sub_categories'=>array('name'=>$categories[$i-2]))
);
}
}
echo "<pre>";
print_r($categories2);
echo "</pre>";
A simple option is to loop over the $input array, building the $output array from inside to out.
$output = array();
foreach ($input as $name) {
if (empty($output)) {
$output = array("name" => $name);
} else {
$output = array("name" => $name, "sub_category" => $output);
}
}
I am trying to create an array using foreach which is used inside an another array.
$team = array();
foreach ($items as $item) {
$team[] = array($item->post_title => $item->post_title, );
}
print_r($team);
$meta_boxes[] = array(
'title' => __( 'Team', 'meta-box' ),
'fields' => array(
array(
'name' => __( 'Select', 'meta-box' ),
'options' => $team,
),
)
);
The options array should be in the format of
'options' => array(
'value1' => ('Label1'),
'value2' => ('Label2'),
),
The print_r output is
Array (
[0] => Array ( [Jessi] => Jessi )
[1] => Array ( [Adam] => Adam )
[2] => Array ( [Babu] => Babu )
)
I am getting output as Array,Array,Array in selectbox for which I am trying to use this for. How do I fix this?
Thanks
Add Key in array [$item->post_title] and assign the values
$team = array();
foreach ($items as $item) {
$team[$item->post_title] = $item->post_title;
}
print_r($team);
Try with -
foreach ($items as $item) {
$team[$item->post_title] = $item->post_title;
}
You can also try like this
$team = array();
foreach ($items as $item) {
$team = array_merge($team,array($item->post_title => $item->post_title));
}
I would like to automatically add records to the new associative array using a foreach loop. I have an array with the names of the following DOM elements:
$DOM = array('element2','element22','element222','element2222');
and a new associative array:
$NEW = array(
'element1' => '',
'element2' => '',
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
Now using a foreach loop would add a new record/array to $NEW array:
foreach($DOM as $name){
//Do something
}
expected result:
$NEW = array(
'element1' => '',
'element2' => array(
'element22' => array(
'element222' => array(
'element2222' => ''
)
)
),
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
You can do something like that? automate this process?
If I understand correctly, $DOM contains keys to create nested array, with empty string value on deepest level. So you have to create such array:
$new_array = array();
$last = &$new_array;
foreach($DOM as $name){
$last[$name] = array();
$last = &$last[$name];
}
$last = '';
unset($last);
And merge it recursively with $NEW:
$NEW = array_merge_recursive($NEW, $new_array);
you can use array_push() function
check this mabe help :
$DOM = array('element2','element22','element222','element2222');
$NEW = array('element1' => '', 'element2' => '', 'element3' => array('element33' => array('element333' => '')));
array_push($NEW, $DOM);
print_r($NEW);
see here :
php.net/manual/en/function.array-push.php
or here :
www.w3schools.com/php/func_array_push.asp
You can modify arrays in foreach-loops by passing them as references:
foreach($array as &$value)
$value[] = $DOM
edit:
<?php
$DOM = array('element2','element22','element222','element2222');
$NEW = array(
'element1' => '',
'element2' => '',
'element3' => array(
'element33' => array(
'element333' => ''
)
)
);
function insert(&$array, $ins) {
$element = array_shift($ins);
if($element == null) return;
foreach($array as $k => &$v) {
if($k === $element) {
$v[current($ins)] = '';
insert($v, $ins);
}
}
}
insert($NEW, $DOM);
var_dump($NEW);
How can I edit this foreach loop so that I will be able to use strpos to look if q is found in the label ?
The result array will contain those values.
$q may be anna or ann or reas john
<?php
$q = $_GET["q"];
if (!$q) return;
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
array_push($result, array(
"label" => $value["label"],
"category" => $value["category"]
));
}
$json = json_encode($result);
echo $json;
?>
This will output every array in $data where $q is somewhere in 'label'.
<?php
if( !isset( $_GET["q"] )) return;
$q = $_GET["q"];
$data = Array(
Array(
'label' => 'anna c13',
'category' => 'Products'
),
Array(
'label' => 'anders andersson',
'category' => 'People'
),
Array(
'label' => 'andreas johnson',
'category' => 'People'
)
);
$result = array();
foreach ($data as $value) {
if( strpos( $value['label'], $q ) !== false ) {
$result[] = $value;
}
}
$json = json_encode($result);
echo $json;
?>
You haven't defined keys for your $data array - so it automatically take the form of:
array(
0=>array(...),
1=>array(...),
2=>array(...)
)
This means that you're using strtolower on an int - so that's probably why it's failing.
foreach ($data as $value) {
if(strpos($value['label'], $q) !== false){
$result[] = $value;
}
}