This is my for each loop
foreach ($row as $key => $value) {
echo $key;
}
The result is:
one
four
end
three
two
I want now that the $key end is always at the end. Is this possible?
Something like
foreach ($row as $key => $value) {
if($key == "end"){
echo $key as last;
} else {
echo $key;
}
}
So that the result is
one
four
three
two
end
As mentined in my comment, simply add the static value to the end of your array
array_push($row, "end");
If you want you can create a custom function , pass your array to a function. Inside that function you could filter the data the way you want .I have created formatRow() function , it just remove the key that you want at last from the array , and insert it again , as the new value are always inserted at end of array , you get the desired output
$row = array(
'one'=>"data",
'four'=>"data",
'end'=>"enddata",
'three'=>"data",
'two'=>"data",
);
$formatted_row = formatRow($row,'end');
echo "<pre>";
var_dump($formatted_row);
//output
// array(5) {
// ["one"]=>
// string(4) "data"
// ["four"]=>
// string(4) "data"
// ["three"]=>
// string(4) "data"
// ["two"]=>
// string(4) "data"
// ["end"]=>
// string(7) "enddata"
// }
function formatRow ($row,$key_that_you_need_last) {
if (array_key_exists($key_that_you_need_last,$row)) {
$value = $row["$key_that_you_need_last"];
unset($row["$key_that_you_need_last"]);
$row["$key_that_you_need_last"] = $value;
}
return $row;
}
If you want to achieve more ,these are the links that you might wanna go through.
array_map
array_walk
Related
Really struggling with this. I have a multidimensional array n levels deep. Each 'array level' has information I need to check (category) and also check if it contains any arrays.
I want to return the category ids of all the arrays which have a category and do not contain an array (i.e. the leaves). I can echo output properly, but I am at a loss as how to return the ids in an array (without referencing)
I have tried RecursiveIteratorIterator::LEAVES_ONLY and RecursiveArrayIterator but I don't think they work in my case? (Maybe I am overlooking something)
$array
array(2) {
["1"]=>
string(5) "stuff"
["2"]=>
array(2) {
["category"]=>
string(1) "0"
["1"]=>
array(3) {
[0]=>
array(3) {
["category"]=>
string(1) "1"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["category"]=>
string(1) "2"
["1"]=>
string(5) "stuff"
["2"]=>
string(5) "stuff"
}
[1]=>
array(5) {
["1"]=>
string(5) "stuff"
["32"]=>
string(5) "stuff"
}
}
}
}
My function
public function recurs($array, $cats = [])
{
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$this->recurs($value, $cats);
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return $array_cat;
}
}
Calling it
$cats_array = $this->recurse($array)
Output echoed
echoing the category here works fine: 1
echoing the category here works fine: 2
How do I return the ids in an array to use in the $cats_array variable?
EDIT: The output should match the echo, so I should get an array containing (1, 2) since they are the only arrays with categories and no arrays within them
array(2){
[0]=>
int(1) "1"
[1]=>
int(1) "2"
}
If I understood you correctly this function will do the job:
function getCategories(array $data)
{
if ($subArrays = array_filter($data, 'is_array')) {
return array_reduce(array_map('getCategories', $subArrays), 'array_merge', array());
};
return array_key_exists('category', $data) ? array($data['category']) : array();
}
If the array contains any sub-arrays they will be returned by array_filter and you will enter the if statement. array_map will apply the function recursively to the sub-arrays and array_reduce will merge the results.
If the array doesn't contain any sub-arrays you will not enter the if statement and the function will return an array with the category if it is present.
Note that you might need to use array_unique to return unique categories.
Also for small performance optimization instead of array_key_exists you can use isset($array[$key]) || array_key_exists($key, $array).
Update
If you want to update your function to make it work you have to recursively collect and merge the sub results. In the following example I introduced a new variable for this:
public function recurs($array, $cats = [])
{
$result = [];
$array_cat = '';
$has_array = false;
// Check if an id exists in the array
if (array_key_exists('category', $array)) {
$array_cat = $array['category'];
}
// Check if an array exists within the array
foreach ($array as $key => $value) {
if (is_array($value)) {
$has_array = true;
$result = array_merge($result, $this->recurs($value, $cats));
}
}
// If a leaf array
if (!$has_array && is_numeric($array_cat)) {
echo "echoing the category here works fine: " . $array_cat . "\n";
return [$array_cat];
}
return $result;
}
I have an array which contents data that I can see on doing a var_dump() but I am unable to iterate through its content using foreach()
The var_dump() generates the following output
array(4) { [0]=> array(1) { [0]=> string(5) "Admin" } [1]=> array(1) { [0]=> string(4) "rick" } [2]=> array(1) { [0]=> string(6) "techbr" } [3]=> array(1) { [0]=> string(7) "testdom" } }
I want to be able to get the content of this array and store it in another.
Currently I am using the following code
$empList = array();
$empList = emp_list($mysqli);
var_dump($empList);//This generated the above output
foreach ($empList as $value)
{
echo $value."<br>";
}
Output of the echo is this
Array
Array
Array
Array
How do I sort this out?
Thank you for your suggestions I have modified the code this way
$i=0;
$empList = array();
$tempList = array();
$tempList = emp_list($mysqli);
foreach ($tempList as $value)
{
$empList[$i] = $value[0];
$i++;
}
Now the $empList array stores stuff in the correct format
It has an array inside another array so, use two foreach loops
$empList = array();
$empList = emp_list($mysqli);
foreach ($empList as $value)
{
foreach ($value as $temp)
{
echo $temp."<br>";
}
}
As u_mulder says in the comments on your question, your array isn't an array of strings - it's an array of more arrays. var_dump() is designed to deal with complicated nested contents, but echo can't print arrays - that's why it's just telling you that each item in $empList is an array, and not what its contents are.
If you wanted to get the content out of a specific array in $empList you'd need to access it by its index key, with something like:
$first = $empList[0];
foreach ($first as $value) {
echo $value."<br>";
}
Or if you wanted to iterate through them all you could just put two foreach loops one inside the other.
I am trying to get certain values from an array but got stuck. Here is how the array looks:
array(2) {
[0]=>
array(2) {
["attribute_code"]=>
string(12) "manufacturer"
["attribute_value"]=>
string(3) "205"
}
[1]=>
array(2) {
["attribute_code"]=>
string(10) "silhouette"
["attribute_value"]=>
array(1) {
[0]=>
string(3) "169"
}
}
}
So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.
foreach ($array as $k => $v) {
$vMine[] = $v['attribute_value'];
}
What I am missing here?
Thank you!
If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:
$vMine = array();
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) { // check if its an array
// if yes merge their contents
$vMine = array_merge($vMine, $v['attribute_value']);
} else {
$vMine[] = $v['attribute_value']; // if just a string, then just push it
}
}
I suggest you to use array_map instead of for loop. You can try something like this..
$vMine = array_map(function($v) {
return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);
print '<pre>';
print_r($vMine);
Try the shorthand version:
foreach ($array as $k => $v) {
$vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}
or the longer easier to understand version, both is the same:
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) {
$vMine[] = current($v['attribute_value']);
} else {
$vMine[] = $v['attribute_value'];
}
}
This question already has answers here:
How to access a specific value in a mixed object(stdClass) and array construct?
(2 answers)
Closed 8 years ago.
var_dump($resultData);
gives me this
array(3) {
[0]=>
object(stdClass)#1 (2) {
["name"]=>
string(12) "filterName_1"
["value"]=>
string(8) "language"
}
[1]=>
object(stdClass)#2 (2) {
["name"]=>
string(9) "country_1"
["value"]=>
string(0) ""
}
[2]=>
object(stdClass)#3 (2) {
["name"]=>
string(10) "language_1"
["value"]=>
string(4) "UAE1"
}
}
How to itrate and get the values ?
tried
echo $resultData["name"];
and some other combinations but cannot make it work.
EDIT : NOTE :
As i have to get the loop of 3 items and its values i need to get the value in the loop as
for ($i=0; $i+3 <= count($resultData); $i=$i+3)
{
}
is there a way without foreach looping?
May you should try
<?php
foreach($resultData as $key => $value) {
echo $value->name; // Give you all names
}
Another example:
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
foreach($resultData as $key => $value) {
// Iterate the required keys
foreach($requiredKeys as $reqVal) {
// Check, if propertie exists in current object
if(isset($value->{$reqVal}) {
echo $value->{$reqVal}; // Give you all names
}
}
}
Example without foreach (for-loop):
<?php
// Set keys you need to print
$requiredKeys = array('name', 'value');
// Iterate the array
for($currentElement = 0; $currentElement <= count($resultData) as $currentElement++) {
// Iterate the required keys
for($reqCounter = 0; $reqCounter <= count($requiredKeys); $reqCounter++) {
// Check, if propertie exists in current object
if(isset($resultData[$currentElement]->{$requiredKeys[$reqCounter]}) {
echo $resultData[$currentElement]->{$requiredKeys[$reqCounter]}; // Give you all names
}
}
}
$resultData is an array containing multiple objects, therefore the first object can be accessed with $resultData[0] and so on.
The objects have a property named name, which can be accessed with $object->name
If you have more than one object in the array, then you can loop through the values contained in the array with foreach. For example:
foreach ($resultData as $object) {
if($object->name === MY_NAME) {
echo $object->value;
}
}
This will take each object in the array and display its value if its name equals MY_NAME.
echo $resultData[0]->name;
Give that a try
I have an array of JSON objects that look like this:
{"id":1,"place":2,"pic_name":"aaa.jpg"}
My PHP file receives a simple array like:
["4","3","1","2","5"]
These numbers correspond to the place value in my JSON object. Now I need to compare the place of each element in the secont array with the value of ID in the JSON object and if the match I have to replace the value of PLACE with the element from the array.
I am having problems doing the comparison. Any guidelines? What I come up with:
foreach($ids as $index=>$id) { //the array
$id = (int) $id;
foreach ($obj as $key=>$value) { //the JSON objects
foreach ($value as $k=>$v){
if ($id != '' && array_search($index, array_keys($ids)) == $value[$k]['id']) {
$value[$k]['place'] = $id;
file_put_contents($file, json_encode($ids));
} else { print "nope";}
} } }
That will be:
$array = [
'{"id":1,"place":2,"pic_name":"aaa.jpg"}',
'{"id":2,"place":5,"pic_name":"aab.jpg"}',
'{"id":3,"place":1,"pic_name":"aba.jpg"}',
'{"id":4,"place":3,"pic_name":"baa.jpg"}',
'{"id":5,"place":4,"pic_name":"abb.jpg"}'
];
$places = ["4","3","1","2","5"];
$array = array_map(function($item)
{
return json_decode($item, 1);
}, $array);
foreach($array as $i=>$jsonData)
{
if(false!==($place=array_search($jsonData['id'], $places)))
{
$array[$i]['place'] = $place+1;
}
}
$array = array_map('json_encode', $array);
//var_dump($array);
-with output like:
array(5) {
[0]=>
string(39) "{"id":1,"place":3,"pic_name":"aaa.jpg"}"
[1]=>
string(39) "{"id":2,"place":4,"pic_name":"aab.jpg"}"
[2]=>
string(39) "{"id":3,"place":2,"pic_name":"aba.jpg"}"
[3]=>
string(39) "{"id":4,"place":1,"pic_name":"baa.jpg"}"
[4]=>
string(39) "{"id":5,"place":5,"pic_name":"abb.jpg"}"
}