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'];
}
}
Related
I want to create a list of variables from a foreach loop. I have an array like so
array(5) {
[0]=> string(105) "http://a4.mzstatic.com/us/r30/Purple5/v4/06/f2/02/06f20208-1739-4fda-c87f-171d73b912a7/screen480x480.jpeg"
[1]=> string(105) "http://a1.mzstatic.com/us/r30/Purple1/v4/53/89/0b/53890b90-c6a5-4db3-cfb9-d6314bf9cfd1/screen480x480.jpeg"
[2]=> string(105) "http://a3.mzstatic.com/us/r30/Purple1/v4/8f/31/b3/8f31b351-c9d7-e545-0ace-e09fcb390264/screen480x480.jpeg"
[3]=> string(105) "http://a5.mzstatic.com/us/r30/Purple3/v4/e7/5f/de/e75fde7b-dc5f-5b26-e531-abf07c409317/screen480x480.jpeg"
[4]=> string(105) "http://a1.mzstatic.com/us/r30/Purple3/v4/27/ce/c6/27cec64e-7e6d-7135-cc76-d0132151dadb/screen480x480.jpeg"
}
and I'd like to assign each to it's own variable. I want the final output to be something like
$var0 = "first array url";
$var1 = "second array url";
etc...
I think I want something like this but it's not quite the right syntax.
foreach ($array as $key => $value) {
$var[$key] = $value;
}
Any ideas?
foreach($array as $key => $value) {
${"var{$key}"} = $value;
}
The function you are searching for is extract.
Just use it after your foreach loop given in your example.
$vars = [];
foreach ($array as $i => $value) {
$vars['var'.$i] = $value;
}
extract($vars);
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"}"
}
This code should explain it all..
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $k => $type) {
$preview[] = $type['type'];
}
if ($preview == 'header_preview'){
echo $preview;
// I will loop content here based on the $section loop NOT the $type loop
}
}
I just need to get each $section['fields'] then outside that loop, which again gets a list of all the $section['fields'] then use one of those field types to create an if statement. The above is non working, I will show you working code here.
foreach($this->sections as $k => $section){
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview'){
//I work but im in a nested loop I need out
}
}
//The main loop here.. the above loop is just to setup data to use inside this loop? Make sense? I hope!
}
I hope this makes sense...
Snippet of var_dump $this->sections
array(26) { ["general"]=> array(3) { ["title"]=> string(7) "General" ["icon"]=> string(106) "img/icons/sub.png" ["fields"]=> array(5) { [0]=> array(6) { ["id"]=> string(10) "responsive" ["type"]=> string(6) "switch" ["title"]=> string(35) "Responsive" ["desc"]=> string(10) "Responsive" ["options"]=> array(2) { [1]=> string(2) "On" [0]=> string(3) "Off" }
It could be possible $k has been duplicated and therefore the loop doesn't know what to do. You can try changing $k to $x, see if it works.
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
foreach($preview as $elem){
if ($elem == 'header_preview'){
echo($elem);
}
}
}
Hmm... Maybe
foreach($this->sections as $k => $section){
$preview = array();
foreach ($section['fields'] as $x => $type) {
$preview[] = $type['type'];
}
if(!in_array('header_preview', $preview)){
// Here $preview DOES NOT contain 'header_preview'
// Do stuff
}
}
$header_preview=false;
foreach($this->sections as $k => $section){
$header_preview=false;// reset the var $header_preview
foreach ($section['fields'] as $k => $type) {
if ($type['type'] == 'header_preview') $header_preview = true;
}
if($header_preview==true){
//here you can add or extract from this array that has `header_preview` value for one of it's field type
}
}
I try to read some keys of an array like
array(3) {
["poste5:"]=> array(3) { [0]=> string(7) "APPLE:" [1]=> string(5)
"demo1" [2]=> string(5) "demo2" }
["services:"]=> array(4) { [0]=> string(9) "orange" [1]=>
string(5) "demo3" [2]=> string(5) "demo4" [3]=> string(5) "demo1" }
["essai:"]=> array(2) { [0]=> string(6) "sd" } }
I try to read this name : poste5 , services , essai
If i use :
foreach ($this->aliasRead as $key => $value){
echo array_keys($this->aliasRead[$key]);
}
I have : Array()
But if i use :
foreach (array_keys($this->aliasRead) as $key => $value2) {
echo $value2;
}
I have poste5 , services , essai
I try to use with this loop foreach ($this->aliasRead as $key => $value){
because i have another traitment after.
How to collect this key of my first loop in this loop foreach ($this->aliasRead as $key => $value){ ?
You already have what you want here:
foreach ($this->aliasRead as $key => $value){
echo $key; // key of the value in the array
print_r($value); // value of $this->aliasRead[$key] which in turn is another array
}
Edit: The reason your second loop works is because of this: array_keys($this->aliasRead[$key]) returns a new array containing the keys of the old array as its values. So $myNewArray = array_keys($this->aliasRead[$key]) is the same as $myNewArray = array('poste5','services','essai'). So, when you loop over this new array like this:
foreach ($myNewArray as $key => $value2) {
echo $value2;
}
$value2 contains your values, which are the keys of your first array, and $key will be 0, 1 and 2 after each step through the loop.
Try this,
$keys = array_keys($this->aliasRead);
print_r($keys);
Or
$keys = array();
foreach ($this->aliasRead as $key => $value){
$keys[] = $key;
}
It's because you're trying to echo an array. This will always give you the string "Array". If you want to see the array's contents, try
var_dump(array_keys($this->aliasRead[$key]));
By the way, in the foreach statement you posted, $this->aliasRead[$key] will be the equal to $value. So this will work as well:
var_dump(array_keys($value));
I have an associative array in php. When I am doing a die on it, then I am getting proper values as follows:
array(1) { [0]=> array(1) { [123]=> string(5) "Hello" }}
But when I am trying extract out keys of this array into an new array, then I am not able to get keys out:
$uniqueIds = array_keys($myAssociativeArray);
die(var_dump($uniqueIds));
int(0) array(1) { [0]=> int(0) }
Can any one tell me what I am doing wrong here? I want to get all the keys out of my associative array. And for this, I am referring to thread: php: how to get associative array key from numeric index?
$uniqueIds = array_keys($myAssociativeArray[0]);
<?php
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$result = multiarray_keys($myAssociativeArray);
var_dump($result);
?>
The following recursively gets all the keys in an associative array
function getArrayKeysFlat($array) {
if(!isset($keys) || !is_array($keys)) {
$keys = array();
}
foreach($array as $key => $value) {
$keys[] = $key;
if(is_array($value)) {
$keys = array_merge($keys,getArrayKeysFlat($value));
}
}
return $keys;
}