Issue with the loop foreach php - php

sorry if my question seems stupid, I'm new to php.
I try to create a loop on my array but the loop returns me only the last value.
I don't understand and I tried everything
$categories = array('name' => 'mamals', 'id' => '1');
$categories = array('name' => 'birds','id' => '2');
$categories = array('name' => 'fishs', 'id' => '3');
$categories = array('name' => 'reptiles', 'id' => '4');
$category = $categories;
foreach($category as $key =>$categ){
echo $categ;
}
It return only "reptiles 4" !
Thank you for you answers

You are overwriting the variable categories, i modified the code by initializing the categories with an empty array, then pushing your entries in it.
$categories = [];
array_push($categories, array('name' => 'mamals', 'id' => '1'));
array_push($categories, array('name' => 'birds','id' => '2'));
array_push($categories, array('name' => 'fishs', 'id' => '3'));
array_push($categories, array('name' => 'reptiles', 'id' => '4'));
foreach($categories as $key=>$categ){
echo "ID: " . $categ["id"] . ", NAME: " . $categ["name"];
}

I response to shunz19's anwser where I said:
It would help to show the shorthand for this mechanism as well. I don't think anyone would use array_push in this sitation.
Here is a more concise solution:
Cause:
You are overwriting your variable - $categories - each time you use =.
So after line 3 the only value in $categories is :
categories = array('name' => 'reptiles', 'id' => '4');
Step By Step:
You look like you want to be adding entries to the Categories multidimensional array. Therefore you need to tell PHP to add not to overwrite, typically with the [] indicating the value is to be inserted into a new (incremental) variable key.
$categories = array('name' => 'mamals', 'id' => '1');
$categories[] = array('name' => 'birds','id' => '2');
This will increment the key index (numeric) by 1 and set the value of array into that key.
It is standard practise to establish numeric arrays and then populate them with this style of referencing.
But this isn't quite simple...
Because your parent array contains sub-arrays, your foreach will give warnings and errors because:
Warning: Array to string conversion in /home/user/scripts/code.php on line XX
Can you see why?
Yes, because your foreach is only opening the parent array, not the child arrays so the data types within are still arrays, but you want to output them as if they're strings.
How can you do this? With a fun little function called print_r().
Concise Solution and Fix:
$categories = []; // Establish the var type is an array.
$categories[] = array('name' => 'mamals', 'id' => '1'); // Add to the array.
$categories[] = array('name' => 'birds','id' => '2'); // add more,...
$categories[] = array('name' => 'fishs', 'id' => '3');
$categories[] = array('name' => 'reptiles', 'id' => '4');
$category = $categories;
foreach($category as $key =>$categ){
print_r($categ);
}
Output:
Array
(
[name] => mamals
[id] => 1
)
Array
(
[name] => birds
[id] => 2
)
Array
(
[name] => fishs
[id] => 3
)
Array
(
[name] => reptiles
[id] => 4
)
Code Example:
You can alternatively just access the array names from the froeach such as:
foreach($category as $key =>$categ){
print $categ['name']."\n"; // will list each name starting at the lowest array key.
}
See my test code here.

Related

Laravel/PHP create an array from array

Hey guys I'm confused about how to create an array using specific keys from my pre-existing array.
Laravel controller
public function index()
{
$content = Page::find(1)->content->toArray();
return View::make('frontend.services', compact('content'));
}
$content is an array that looks similar to
array (
0 => array (
'id' => '1',
'page_id' => '1',
'name' => 'banner_heading',
'content' => 'some content', ),
1 => array (
'id' => '2',
'page_id' => '1',
'name' => 'banner_text',
'content' => 'some other content' )
)
And I want it recreate this array to look like this
array (
0 => array (
'banner_heading' => 'some content'
),
1 => array (
'banner_text' => 'some other content'
)
)
How can I move the keys name and content to equal their values as a single row in the array?
I greatly appreciate any advice.
PHP >= 5.5.0:
$result = array_column($content, 'content', 'name');
PHP < 5.5.0:
foreach($content as $key => $array) {
$result[$key] = array($array['name'] => $array['content']);
}
You mean
$newContent = array();
foreach ($content as $record) {
$newContent[] = array($record['name'] => $record['content']);
}
?
I don't know Laravel, but i believe that your solutions should be similar to this :
$newArray= array();
foreach($content as $key => $value)
{
$newArray[] = $value["banner_heading"];
}
return View::make('frontend.services', compact('newArray'));
Or at least it should be something similar with this.

Foreach a specific key from array

I have an array with 2 same keys i want to foreach out if possible. The currently code looks like:
$arrayName = array(
1 => array('detail' => 'detail1' , 'detail' => 'detail2')
);
foreach ($arrayName[1] as $key['detail'] => $value) {
echo $value;
}
Thanks for any help!
Your keys are overwriting themselves. You may want to approach the solution like this:
$arrayName = array(
array('name' => 'detail' , 'value' => 'detail1'),
array('name' => 'detail' , 'value' => 'detail2')
);
foreach ($arrayName as $i) {
echo $i['value'];
}
You cannot have identical keys for an array.. The final key overwrites the first one. (in your case)
From the PHP Docs..
If multiple elements in the array declaration use the same key, only
the last one will be used as all others are overwritten.
A dynamic way of doing this..
<?php
$new_arr = array();
foreach(range(1,5) as $v)
{
$new_arr['detail'.$v]='detail'.$v;
}
print_r($new_arr);
OUTPUT :
Array
(
[detail1] => detail1
[detail2] => detail2
[detail3] => detail3
[detail4] => detail4
[detail5] => detail5
)

multidimensional array - adding a key and value where a key and value is matched

I'm trying to add a key and value (associative) from an array to another array, where one specific key and value match. Here are the two arrays:
$array1 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2'
),
2 => array(
'walmart' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'milk' => 'product3'
)
);
$array2 = array(
1 => array(
'walgreens' => 'location',
'apples' => 'product1',
'oranges' => 'product2',
'bananas' => 'product3',
)
);
Here is the attempt I made at modifying $array1 to have key 'bananas' and value 'product3':
$dataCJ = getCJItem($isbn);
foreach ($array1 as $subKey => $subArray) {
foreach($subArray as $dkey => $dval){
foreach($array2 as $cjk => $cjv){
foreach($cjv as $cjkey => $cjval){
if($dval['walgreens'] == $cjval['walgreens']){
$dval['bananas'] = $cjval['bananas'];
}
}
}
}
}
This doesn't work. How can I fix this?
Change => $dval to => &$dval. Currently you are creating and writing to a new variable and the update will not work in-place.
I would look at array_merge() function!
Here is a start with the PHP doc.
For your specific case, you could do the following :
foreach($array1 as $key1 => $values1){
foreach($array2 as $key2 => $values2){
if($values1[0] == $values2[0]){
$array1[$key1] = array_merge($values1, $values2);
}
}
}
Note to simplify the problem you should inverse the first key=> value pair of the array.
Having an array this way would be a lot simper :
array(
'location' => "The location (eg:walgreens)",
//...
);
This way you could change the comparison to the following instead :
$values1['location'] == $values2['location']
Which would be safer in the case the array is not built with the location as the first pair.

How to extract data out of a specific PHP array

I have a multi-dimensional array that looks like this:
The base array is indexed based on category ids from my catalog.
$cat[category_id]
Each base array has three underlying elements:
['parent_id']
['sort_order']
['name']
I want to create a function that allows us to create a list of category_id's and names for a given parent_category_id in the correct sort order. Is this possible? Technically it is the same information, but the array is constructed in a weird way to extract that information.
Here is an example definition for the array:
$cat = array();
$cat[32]['parent_id']= 0;
$cat[32]['sort_order']= 1;
$cat[32]['name']= 'my-category-name1';
$cat[45]['parent_id']= 0;
$cat[45]['sort_order']= 0;
$cat[45]['name']= 'my-category-name2';
$cat[2]['parent_id']= 0;
$cat[2]['sort_order']= 2;
$cat[2]['name'] = "my-category-name3";
$cat[3]['parent_id']= 2;
$cat[3]['sort_order']= 1;
$cat[3]['name'] = "my-category-name4";
$cat[6]['parent_id']= 2;
$cat[6]['sort_order']= 0;
$cat[6]['name'] = "my-category-name5";
Assuming it's something of this sort:
$ary = Array(
0 => Array(
'parent_category_id' => null,
'sort_order' => 0,
'name' => 'my-category-name0'
),
1 => Array(
'parent_category_id' => 0,
'sort_order' => 1,
'name' => 'my-category-name1'
),
2 => Array(
'parent_category_id' => 0,
'sort_order' => 2,
'name' => 'my-category-name2'
),
3 => Array(
'parent_category_id' => null,
'sort_order' => 0,
'name' => 'my-category-name3'
),
4 => Array(
'parent_category_id' => 3,
'sort_order' => 0,
'name' => 'my-category-name4'
)
);
You can use a combination of a foreach and usort to achieve what you're going for.
// #array: the array you're searchign through
// #parent_id: the parent id you're filtering by
function getFromParent($array, $parent_id){
$result = Array();
foreach ($array as $category_id => $entry){
if ($entry['parent_category_id']===$parent_id)
$result[$category_id] = $entry;
}
usort($result,create_function('$a,$b','return ($a["sort_order"]>$b["sort_order"]?1:($b["sort_order"]<$a["sort_order"]?-1:0));'));
return $result;
}
var_export(getFromParent($ary,0));
EDIT Sorry, fixed some syntax errors. Tested, and works (at least to result in what I was intending)
EDITv2 Here's the raw output from the above:
array (
0 =>
array (
'parent_category_id' => 0,
'sort_order' => 1,
'name' => 'my-category-name1',
),
1 =>
array (
'parent_category_id' => 0,
'sort_order' => 2,
'name' => 'my-category-name2',
),
)
(Used var_export just for you #FelixKling)
EDITv3 I've updated my answer to go along with the OP's update. I also now make it retain the original "category_id" values in the result array.
First you create an empty array, it will be used to store your result.
$result = array();
You need to iterate through your initial array, you can use foreach().
Then, given your parent_category_id simply use an if statement to check whether it's the given id or not.
If it is, just construct and push your result to your $result array.
Use any of the sort functions you like
Use the magic return $result;
You're done.
function returnSortedParents($categories, $target_parent){
$new_list = array();
foreach($categories as $index => $array){
//FIND ONLY THE ELEMENTS MATCHING THE TARGET PARENT ID
if($array['parent_category_id']==$target_parent){
$new_list[$index = $array['sort_order'];
}
return asort($new_list); //SORT BASED ON THE VALUES, WHICH IS THE SORTING ORDER
}

Matching an array value by key in PHP

I have an array of items:
array(
[0] => array(
'item_no' => 1
'item_name' => 'foo
)
[1] => array(
'item_no' => 2
'item_name' => 'bar'
)
) etc. etc.
I am getting another array from a third party source and need to remove items that are not in my first array.
array(
[0] => array(
'item_no' => 1
)
[1] => array(
'item_no' => 100
) # should be removed as not in 1st array
How would I search the first array using each item in the second array like (in pseudo code):
if 'item_no' == x is in 1st array continue else remove it from 2nd array.
// Returns the item_no of an element
function get_item_no($arr) { return $arr['item_no']; }
// Arrays of the form "item_no => position in the array"
$myKeys = array_flip(array_map('get_item_no', $myArray));
$theirKeys = array_flip(array_map('get_item_no', $theirArray));
// the part of $theirKeys that has an item_no that's also in $myKeys
$validKeys = array_key_intersect($theirKeys, $myKeys);
// Array of the form "position in the array => item_no"
$validPos = array_flip($validKeys);
// The part of $theirArray that matches the positions in $validPos
$keptData = array_key_intersect($theirArray, $validPos);
// Reindex the remaining values from 0 to count() - 1
return array_values($keptData);
All of this would be easier if, instead of storing the key in the elements, you stored it as the array key (that is, you'd be using arrays of the form "item_no => item_data") :
// That's all there is to it
return array_key_intersect($theirArray, $myArray);
You can also do:
$my_array =array(
0 => array( 'item_no' => 1,'item_name' => 'foo'),
1 => array( 'item_no' => 2,'item_name' => 'bar')
);
$thrid_party_array = array(
0 => array( 'item_no' => 1),
1 => array( 'item_no' => 100),
);
$temp = array(); // create a temp array to hold just the item_no
foreach($my_array as $key => $val) {
$temp[] = $val['item_no'];
}
// now delete those entries which are not in temp array.
foreach($thrid_party_array as $key => $val) {
if(!in_array($val['item_no'],$temp)) {
unset($thrid_party_array[$key]);
}
}
Working link
If your key is not actually a key of your array but a value, you will probably need to do a linear search:
foreach ($itemsToRemove as $itemToRemove) {
foreach ($availableItems as $key => $availableItem) {
if ($itemToRemove['item_no'] === $availableItem['item_no']) {
unset($availableItems[$key]);
}
}
}
It would certainly be easier if item_no is also the key of the array items like:
$availableItems = array(
123 => array(
'item_no' => 123,
'item_name' => 'foo'
),
456 => array(
'item_no' => 456,
'item_name' => 'bar'
)
);
With this you could use a single foreach and delete the items by their keys:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$itemToRemove['item_no']]);
}
You could use the following to build an mapping of item_no to your actual array keys:
$map = array();
foreach ($availableItems as $key => $availableItem) {
$map[$availableItems['item_no']] = $key;
}
Then you can use the following to use the mapping to delete the corresponding array item:
foreach ($itemsToRemove as $itemToRemove) {
unset($availableItems[$map[$itemToRemove['item_no']]]);
}

Categories