reconstruct an array to remove a parent in PHP - php

i want to restructure my array so that it looks better in a json
here is a print_r of my current variable:
Array
(
[0] => Array
(
[item_id] => 2
)
[1] => Array
(
[item_id] => 1
)
[2] => Array
(
[item_id] => 1
)
)
i want to reconstruct it be like this or similar:
EDIT
Array
(
[item_id] = array([0]=>'2',[1]=>'1', [2]=>'1');
)
sorry for my poor english m(_ _)m
i just want the item_id to have multiple values.

The hurdle
You actually can't in any way produce the output that you desire, since the key needs to be unique.
You can't use a key of item_id more than once, every time you try and set it, it will override what was in there last.
Think about it, how do you then look up the item with key of item_id, you can't, because three things would have that same key.
If the only reason is for cosmetics, I'd leave the output as you currently have it, although it may look a little messy in your JSON, it works.
A different approach
The best you can hope, is to get an output of:
'item_id' => array(
2,
1,
1
)
You can do this with the help of the array_map function:
$array = array('item_id' => array_map('current', $array));

This can be accomplished using this code.
$a['item_id'] = array();
foreach($arr as $key=>$val) {
$a['item_id'][] = $val['item_id'];
}
print_r($a);

$array = array('item_id' => array_map('current', $array));

Related

How to change array keys according the it's elements

I need to change array value based on specific value. Take a look at this array below :
Array
(
[0] => Array
(
[id] => 5
[title] =>
[nomor] => 1
)
[1] => Array
(
[id] => 6
[title] =>
[nomor] => 2
)
)
I need to change the array key based on nomor value. How can I do that?
You can use array_column for that (doc) as:
$arr = array_column($arr, null, "nomor");
Live example
The easiest way is to simply create a new array, loop through your existing one, and save each elements into the new one with the proper key.
foreach($array as $element) {
$formatted_array[$element['nomor']] = $element;
}
Here is a working fiddle:
https://3v4l.org/PlbJ1
Edit: Keep in mind though, if multiple elements have the same value as "nomor", the latest will override the previous one.
Edit 2: Per the other answer, PHP's array_column function seems to do this simpler.

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

PHP array issue

I have an Array List that I want to output like my example below. How can I achieve it in PHP?
Array List:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
Want to output like this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
Thanks,
steamboy
You can use array_combine() and pass two copies of your original array:
$new_list = array_combine($list, $list);
print_r($new_list);
Maps the contents of the first argument as keys and the contents of the second argument as values, in their defined order.
I haven't tested it, but this should work
foreach ($array as $key => $value) {
$array[$value] = $value;
unset($array[$key]);
}
That should do it
That is redundancy at its finest. It makes little sense to have keys matching their values, and probably highlights the need for a design change, or a potential optimisation somewhere in your application. Turning this:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
into this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
effectively reduces the amount of information you are storing, since you the developer know in advance that keys should match values.

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Grouping array values in php

I have an array with some value like this:
[Organization_id] => Array
(
[0] => 4
[1] => 4
[2] => 4
)
but i want some thing like this:
[Organization_id] => Array
(
[0] => 4
)
Thanks in advance..
If you don't care about the key to value association possibly messing up, you can use this:
$array = array_unique($array);
Although array_unique was mentioned twice now, I feel the answers failed to point out that you have to use the function on the nested array and not the array itself, so here is a usage example
$array = array( 'Organization_id' => array(4,4,4) );
$array['Organization_id'] = array_unique( $array['Organization_id'] );
print_r($array);
which will do what you want.

Categories